gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 19:29:06 25 4
gpt4 key购买 nike

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

我想创建一个原型(prototype)和继承它的 child 。原型(prototype)有一个构造函数(或者换句话说,是一个函数)。我希望 children 继承这个构造函数,而不是为每个 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)/父级:

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()

这更符合我想要的代码方式,而不是行为。这种情况导致 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()

最佳答案

需要一段时间才能理解重新定义构造函数的含义。您要做的是在实例化子项时调用父项的构造函数。

所以你不想要这个,即重新分配 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

关于Javascript:继承原型(prototype)而不重新定义构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29248876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com