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

时间:2015-03-25 06:28:28

标签: javascript oop

我在理解javascript继承和构造函数方面遇到了问题,尽管有https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScripthttp://robotlolita.me/2011/10/09/understanding-javascript-oop.html等手册。

我想创建一个原型和继承它的孩子。原型有一个构造函数(换句话说,是一个函数)。 我希望孩子们继承这个构造函数,而不是为每个孩子重新定义构造函数。父母的构造函数会做很多事情,我不想在子代中复制代码。甚至构造函数的参数列表也可能会改变,在这种情况下,我只想在父构造函数中更改它们,而不是每个子元素。

这是一个适用于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 />");

}

定义原型/父级:

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

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

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

这更符合我想要的代码,但不是行为。这种情况导致this.url在子节点中未定义:

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

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

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

1 个答案:

答案 0 :(得分:3)

通过重新定义构造函数需要一段时间来理解你的意思。你想要做的是在实例化孩子时调用父的构造函数。

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

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

请改为:

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

现在,您可以使用以下引用访问子实例中的url和anotherFancyArg: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