Javascript: 继承原型而不重新定义构造函数

Javascript: Inherit form a prototype without redefining the constructor

我在理解 javascript 继承和构造函数时遇到了问题,尽管有 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript and http://robotlolita.me/2011/10/09/understanding-javascript-oop.html.

这样的手册

我想创建一个原型并 children 继承它。原型有一个构造函数(或者换句话说,是一个函数)。 我希望 children 继承这个构造函数,而不是 re-defining 每个 child 的构造函数。 parent 的构造函数将做很多事情,我不想在 children 中重复这些代码。甚至构造函数的参数列表也可能会发生变化,在这种情况下,我只想在 parent 构造函数中更改它们,而不是每个 child。

因此,一个适用于 jsfiddle 的示例(另请参阅 https://jsfiddle.net/9pj1avjh/10/):

首先是 运行 测试的序言和一些节省输入的函数(向前跳过):

function sayHello2(msg,name){
    document.write(name+": "+msg+" "+this.url+"<br />");
}

function runtest(){
    var c = new child('google.com');
    c.sayHello("Website:","dolf");

    var p = new proto("yahoo.com");
    p.sayHello("Website:");

    document.write("<br />");

}

定义 prototype/parent:

var proto = function(url){
    this.url = url
}
proto.prototype.sayHello = function(msg){
    document.write(msg+" "+this.url+"<br />")
}

这是肉。它显示了所需的行为,但这意味着我总是必须在每个 child 中重新定义构造函数,这是我不想要的。

var child = function(url){
    this.url = url
}
child.prototype = Object.create(proto.prototype);
child.prototype.sayHello = sayHello2
runtest()

这更符合我想要的 code-wise,但不是行为。这种情况导致 this.url 在 child 中未定义:

var child = function(){
}
child.prototype = Object.create(proto.prototype);
child.prototype.constructor = proto.prototype.constructor
child.prototype.sayHello = sayHello2
runtest()

这也不起作用,因为它导致 sayHello2 也被用于 proto 而不仅仅是 child

var child = proto.prototype.constructor
child.prototype = Object.create(proto.prototype);
child.prototype.sayHello = sayHello2
runtest()

需要一段时间才能理解您所说的重新定义构造函数的含义。您要做的是在实例化 child.

时调用 parent 的构造函数

所以你不想要这个,即重新分配 this.url = url,对吧?

var child = function(url, anotherFancyArg){
    this.url = url;
    this.anotherFancyArg = anotherFancyArg;
}

改为这样做:

var child = function(url, anotherFancyArg){
    proto.apply(this, arguments);
}

现在您可以使用此引用在 child 实例中访问 url 和另一个 FancyArg:this.urlthis.anotherFancyArg,例如

var c = new child('google.com', 'abc');
console.log(c.url); // you get google.com here

我还注意到一件事。这是错误的:

child.prototype = Object.create(proto.prototype);
child.prototype.constructor = proto.prototype.constructor;

改为这样做:

child.prototype = Object.create(proto.prototype); // you inherit from parent's prototype
child.prototype.constructor = child; // but you instantiate the child object