我有一个原型继承,如下所示,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();
constructor.prototype
与prototype.constructor
的差异?我们有javascript中的constructor.prototype吗?发布于 2016-02-20 13:56:08
Student.prototype = new Guru()
因为Guru
构造函数需要一个实例,而不是一个子类。在该构造函数中创建的属性应直接分配给实例。
在你的例子中,这并不重要,但是想象一下:
function C1() { this.o = []; }
function C2() {}
C2.prototype = new C1();
var c1a = new C1(), c1b = new C1(),
c2a = new C2(), c2b = new C2();
c1a.o.push(123);
c2a.o.push(456);
c1b.o; // [] -- The property is NOT shared among C1 instances
c2b.o; // [456] -- The property is shared among all Sub instances
stu.constructor
和stu.__proto__
有什么区别?创建Student
构造函数时,它会自动接收带有指向Student
的constructor
属性的prototype
。
相反,__proto__
是一个getter,它返回对象的[原型]。注意,这不是很多标准(它只在浏览器附件中定义),您应该使用Object.getPrototypeOf
。
因此,stu.constructor
(从Student.prototype
继承)是Student
。stu.__proto__
(从Object.prototype
继承)是Student.prototype
。
constructor.prototype
与prototype.constructor
的区别在原型上使用constructor.prototype
是没有意义的,因为它提供了相同的原型(假设它没有被更改)。
在实例上使用constructor.prototype
提供它继承的原型(假设它没有阴影,也没有被修改)。
在构造函数上使用prototype.constructor
是没有意义的,因为它提供了相同的构造函数(假设它没有被更改)。
https://stackoverflow.com/questions/35529371
复制