JavaScript继承,重置原型构造函数?
下面是实例继承的一个基本示例:JavaScript继承,重置原型构造函数?,javascript,inheritance,Javascript,Inheritance,下面是实例继承的一个基本示例: 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, {
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();
下面是一个没有继承的相同函数的示例:
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;
原型构造器是本机对象构造器,之后它是在其上声明原型的对象/函数
这句话对较老的浏览器来说是必要的吗?是有必要打击一些流行的坏技术吗?还是我没有正确地进行原型继承?感谢Ibrahim指出,在这两种情况下,我都在重写B.prototype 鉴于此,似乎: 一, 二,
应保持原始原型构造函数完好无损。在这两种情况下,您都使用新对象覆盖
B.prototype
。因此,构造函数
不见了(您必须重置它)。您可以向分配给B.prototype
的对象文本添加“构造函数”
属性,例如:B.prototype={constructor:B,write:…}代码>.Object.assign在ES2015规范中定义,如果打算在旧浏览器中使用,则需要使用polyfill。另外,为什么不将函数直接附加到原始原型上呢?(B.prototype.write=fun…)