Please follow the code below,
var fn79 = function(){
var Student = function(_name){
this.name = _name;
};
Student.prototype = function(){
print("Inside Prototype function");
};
//Student.prototype = {}
var obj1 = new Student("Ricky");
Student.prototype.lastName = "Gonzales";
var obj2 = new Student("Jacky");
print(obj1.name+" - "+obj1.lastName);
print(obj2.name+" - "+obj2.lastName);
};
fn79();
The output I get is
D:Rahul ShivsharanMyPractiseJavaScriptCommandLine>java -jar js-14.jar prac.js
- Gonzales
- Gonzales
D:Rahul ShivsharanMyPractiseJavaScriptCommandLine>
From above output you can see I am not able to print "name" property of objects.
now if I change the the code to as below,
var fn79 = function(){
var Student = function(_name){
this.name = _name;
};
/*
Student.prototype = function(){
print("Inside Prototype function");
};
*/
Student.prototype = {}
var obj1 = new Student("Ricky");
Student.prototype.lastName = "Gonzales";
var obj2 = new Student("Jacky");
print(obj1.name+" - "+obj1.lastName);
print(obj2.name+" - "+obj2.lastName);
};
fn79();
I get the desired output as
D:Rahul ShivsharanMyPractiseJavaScriptCommandLine>java -jar js-14.jar prac.js
Ricky - Gonzales
Jacky - Gonzales
D:Rahul ShivsharanMyPractiseJavaScriptCommandLine>
Why my First example was not working properly.
Function is an object itself in javascript.
What I thought is,
Student.prototype = function(){
print("Inside Prototype function");
}
Student's prototype is pointing to function which itself is an object.
So why "name" is not getting printed in my first case, and how prototype assigning to function effects it.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…