Javascript 在构造函数中动态分配原型不起作用
当我们使用“new”操作符为javascript中的对象创建实例时会发生什么?在创建过程中,何时为构造函数分配原型? 我尝试在构造函数中动态分配一个新原型,但结果很奇怪:Javascript 在构造函数中动态分配原型不起作用,javascript,oop,constructor,prototype-programming,Javascript,Oop,Constructor,Prototype Programming,当我们使用“new”操作符为javascript中的对象创建实例时会发生什么?在创建过程中,何时为构造函数分配原型? 我尝试在构造函数中动态分配一个新原型,但结果很奇怪: function Person(name, age){//the super class constructor this.name = name; this.age = age; if (typeof this.sayName != "function") {//set the function in
function Person(name, age){//the super class constructor
this.name = name;
this.age = age;
if (typeof this.sayName != "function") {//set the function in prototype so Person's instance or subType can share just one instance of function(since function in javascript is Object indeed)
Person.prototype.sayName = function(){
console.log("my name is ", this.name);
}
}
}
//if I assign Student's prototype here, not in its constructor, it will be OK, but why not encapsulate it within the constructor if I can?
//Student.prototype = new Person();
function Student(name, age, school, grade){//the subType constructor
Person.call(this, name, age);//get the super class property
this.school = school;//init the subType property
this.grade = grade;
if (!(Student.prototype instanceof Person)) {//just assign the prototype to Student for one time
Student.prototype = new Person();
}
}
let person1 = new Student("Kate", 23, "Middle school", "3.8");
let person2 = new Student("Gavin", 23, "Middle school", "3.8");
let person3 = new Student("Lavin", 23, "Middle school", "3.8");
person1.sayName();//Uncaught TypeError: person1.sayName is not a function
person2.sayName();//my name is Gavin
person3.sayName();//my name is Lavin
函数人(姓名、年龄、父母){//超类构造函数
this.name=名称;
这个。年龄=年龄;
}
//这必须在构造函数/功能人员之外
Person.prototype.sayName=函数(){
log(“我的名字是”,this.name);
}
//学生是否在学生构造函数中创建?
//Student.prototype=新人();
函数学生(姓名、年龄、学校、年级){//子类型构造函数
调用(this,name,age);//获取超级类属性
this.school=school;//初始化子类型属性
这个。等级=等级;
}
//检查此项以了解为什么这是在js中继承的好方法http://stackoverflow.com/a/17393153/1507546
Student.prototype=Object.create(Person.prototype);
let person1=新生(“凯特”,23岁,“中学”,“3.8”);
let person2=新生(“Gavin”,23,“中学”,“3.8”);
let person3=新生(“Lavin”,23,“中学”,“3.8”);
person1.sayName()//未捕获类型错误:person1.sayName不是函数
person2.sayName()//我叫加文
person3.sayName()//我叫拉文
当我们使用“new”操作符为javascript中的对象创建实例时会发生什么
以下是您案例的MDN文档:
第一次执行代码new Student(…)时,会发生以下情况:
Student.prototype
。您可以在任何地方调用设置原型代码,但在开始创建新实例之前
下一个实例将使用Person prototype创建 @smarber,谢谢你的解释和链接。但实际上我搞不明白为什么person1不能得到sayName方法,而person2和person3可以?我也很好奇当我们有了一个新的对象后的场景。你应该在他的帖子上发表评论,而不是在你的帖子上,否则他不会得到通知。:)谢谢我查看了MDN文档,现在明白了。链接“感谢您的解释”和链接“stackoverflow.com/a/17393153/1507546”;刚才我检查了MDN文档,现在得到了答案。对于“为什么person1无法获得sayName方法,而person2和person3可以?我很好奇当我们创建一个新对象时的场景”