这是实例继承的基本示例:
function A() {
this.props = {
a: 'a',
b: 'b'
}
}
A.prototype = {
fn: function() {
console.log(this.props);
}
}
function B() {
A.call(this);
}
B.prototype = Object.assign(A.prototype, {
write: function() {
this.fn();
}
});
console.log(B.prototype.constructor); // ƒ Object() { [native code] }
B.prototype.constructor = B;
console.log(B.prototype.constructor); // ƒ B() { A.call(this); }
var b = new B();
这是一个没有继承的相同函数的例子:
function A() {
this.props = {
a: 'a',
b: 'b'
}
}
A.prototype = {
fn: function() {
console.log(this.props);
}
}
function B() {
}
B.prototype = {
write: function() {
console.log('good')
}
}
/*
I don't think anyone advocates setting the prototype constructor
as the Function to which it belongs in this case.
*/
console.log(B.prototype.constructor); // ƒ Object() { [native code] }
B.prototype.constructor = B;
console.log(B.prototype.constructor); // ƒ B() {}
var b = new B();
正如您所看到的,在这两种情况下,在行之前:
B.prototype.constructor = B;
原型构造函数是本机的Object构造函数,之后它是声明原型的Object / Function。
旧版浏览器是否需要该行,是否有必要对抗一些流行的不良技术,还是我没有正确地进行原型继承?
答案 0 :(得分:1)
感谢Ibrahim指出,在这两种情况下,我都压倒了B.prototype。
鉴于此,似乎:
1
B.prototype = Object.assign(B.prototype, A.prototype, {
write: function() {
this.fn();
}
});
2
B.prototype = Object.assign(B.prototype, {
write: function() {
console.log('good')
}
});
应该保留原始原型构造函数。