【发布时间】:2016-02-20 21:38:23
【问题描述】:
我有一个原型继承,如下所示,Student 扩展了Guru。我有三个问题,谁能解释一下。
function Guru(name){
this.name = name;
}
Guru.prototype.copy = function(){
return this.constructor(this.name);
}
function Student(name){
Guru.call(this)
this.name = name;
}
Student.prototype = Object.create(Guru.prototype);
Student.prototype.constructor = Student;
var stu = new Student("John Cena");
console.log(stu.constructor);
console.log(stu.__proto__);
- 我们为什么要避免
Student.prototype = new Guru(); -
这两者有什么区别:
console.log(stu.constructor); console.log(stu.__proto__);打印以下内容:
[Function: Guru] Guru { constructor: [Function: Student] } constructor.prototype和prototype.constructor之间的区别?我们在javascript中有constructor.prototype吗?
【问题讨论】:
-
这里有一些精彩的答案stackoverflow.com/questions/572897/…,尤其是第二个答案。我还建议阅读有关编程范例的文章。
-
每个帖子只问一个问题。
-
你所有的学生都是大师?哇。顺便说一句,
copy方法错过了new。
标签: javascript inheritance prototype