gpt4 book ai didi

javascript - 在 Javascript 中扩展原型(prototype) - 好方法?

转载 作者:数据小太阳 更新时间:2023-10-29 04:29:56 25 4
gpt4 key购买 nike

我想验证在扩展原型(prototype)时我使用的方法是否正确 - 假设“扩展”是正确的词。

这个主题得到了很多克隆。我仍在努力正确理解这个主题...

目的是:- 编写干净和良好的代码。- 避免使用框架,如果可能的话,使用纯 Javascript。- 获得有关不扭曲 JS 以获得启用类的行为的干净框架的建议。

这是我的沙箱的父级原型(prototype):

function Parent(){

}

Parent.prototype = {

"init":function(){

this.name = "anon";
},

"initWithParameters":function(parameters){

this.name = parameters.name ? parameters.name : "anon";
},

"talk": function(){

console.log('Parent is: ' + this.name);
}
}

现在 Child 原型(prototype) - 它添加了一个“position”属性并重新定义了行为:

function Child(){

Parent.call(this);
}


Child.prototype = new Parent;
Child.prototype.constructor = Child;

Child.prototype.init = function(){

Parent.prototype.call(this);

this.setPosition(0, 0);
}

Child.prototype.initWithParameters = function(parameters){

Parent.prototype.initWithParameters.call(this, parameters);

if(!this.position){

this.position = {x:0, y:0};
}

this.setPosition(parameters.pos.x, parameters.pos.y);
}

Child.prototype.setPosition = function(x, y){

this.position.x = x;
this.position.y = y;
}

Child.prototype.talk = function(){

console.log('Child is: ' + this.name + ' and location is: ' + this.position.x + ', ' + this.position.y);
}

这是一个好的做法吗?有没有避免写成“Child.prototype”的速记?覆盖属性时(可能使用文字,就像编写父原型(prototype)一样)。

我知道 J. Resig 的类/扩展方法。但我宁愿使用 Javascript 作为原型(prototype)语言,而不是让它作为一种“类类行为无类 OO 语言”。

感谢您的帮助:-)

最佳答案

一般来说,您的方法会奏效,但更好的方法是替换:

Child.prototype = new Parent;

与:

Child.prototype = Object.create(Parent.prototype);

这样你就不需要调用 new Parent,这有点反模式。您还可以直接定义新属性,如下所示:

Child.prototype = Object.create(Parent.prototype, {
setPosition: {
value: function() {
//... etc
},
writable: true,
enumerable: true,
configurable: true
}
});

希望这对您有所帮助。

Object.create() at MDN

关于javascript - 在 Javascript 中扩展原型(prototype) - 好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28487909/

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