【问题标题】:Javascript: Inherit form a prototype without redefining the constructorJavascript:继承表单原型而不重新定义构造函数
【发布时间】:2015-03-25 06:28:28
【问题描述】:

尽管有 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScripthttp://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


【解决方案1】:

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

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

【讨论】:

  • 谢谢,这确实是我需要的。 “参数”和应用方法是我需要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多