【发布时间】:2015-03-25 06:28:28
【问题描述】:
尽管有 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript 和 http://robotlolita.me/2011/10/09/understanding-javascript-oop.html 这样的手册,但我在理解 javascript 继承和构造函数时遇到了问题。
我想创建一个原型和继承它的孩子。原型有一个构造函数(或者换句话说,是一个函数)。 我希望孩子们继承这个构造函数,而不是为每个孩子重新定义构造函数。父级的构造函数会做很多事情,我不想在子级中复制这些代码。甚至构造函数的参数列表也可能发生变化,在这种情况下,我只想在父构造函数中更改它们,而不是每个子构造函数。
一个适用于 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 在 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()
【问题讨论】:
-
对不起,这个问题我看了三次……还是没看懂。
-
@thefourtheye 我认为 OP 想要的是不必在子构造函数中重新分配
this.url = url。
标签: javascript oop