Javascript 向原型添加属性的最佳模式是什么
下面是我需要的三个添加方法的选项 原型。我想知道是否有什么问题 任何一种模式。使用这样的原型会有不同吗?或者它们都一样,只是写得不同而已 每次运行选项后,我都可以调用Javascript 向原型添加属性的最佳模式是什么,javascript,Javascript,下面是我需要的三个添加方法的选项 原型。我想知道是否有什么问题 任何一种模式。使用这样的原型会有不同吗?或者它们都一样,只是写得不同而已 每次运行选项后,我都可以调用egg().alertMe() 这些只是简单的提问方式 谢谢你的帮助 // option 1 // Methods are added to the egg functions prototype // individually and the newly created // objects prototype points to
egg().alertMe()代码>
这些只是简单的提问方式
谢谢你的帮助
// option 1
// Methods are added to the egg functions prototype
// individually and the newly created
// objects prototype points to this prototype.
var egg = function() {
return new egg.init();
};
egg.prototype.alertMe = function () {alert('alertMe');};
egg.prototype.logMe = function () {console.log('logMe');};
// constructor function
egg.init = function() {};
egg.init.prototype = egg.prototype;
我更喜欢Object.assign(egg.prototype,{…})
@elclanrsObject.assign
非常棒,但是如果您尝试使用getter/setter,请小心,因为它会复制getter的结果。另外,为什么问题中没有对象。创建选项?谢谢你的回答,因为这是用于编写jquery库的模式类型,我正在尝试理解原型。同样在阅读MDN上复制的Object.assign()之后,我只想引用而不是复制。区别在于prototype.constructor
和egg.prototype==init.prototype
。除此之外,:-)谢谢你说的反模式是什么意思?我更喜欢Object.assign(egg.prototype,{…})
@elclanrsObject.assign
非常棒,但是如果你试图使用getter/setter,请小心,因为它会复制getter的结果。另外,为什么问题中没有对象。创建选项?谢谢你的回答,因为这是用于编写jquery库的模式类型,我正在尝试理解原型。同样在阅读MDN上复制的Object.assign()之后,我只想引用而不是复制。区别在于prototype.constructor
和egg.prototype==init.prototype
。除此之外,:-)谢谢你说的反模式是什么意思?
// option 2
// Methods are added to the egg functions prototype
// in an object literal and the newly created
// objects prototype points to this prototype.
var egg = function() {
return new egg.init();
};
egg.prototype = {
// Alert me.
alertMe: function () {alert('alertMe');},
// Log me.
logMe: function () {console.log('logMe');}
};
// constructor function
egg.init = function() {};
egg.init.prototype = egg.prototype;
// option 3
// Just add the methods to the the newly created
// objects prototype.
var egg = function() {
return new egg.init();
};
// constructor function
egg.init = function() {};
egg.init.prototype = {
// Alert me.
alertMe: function () {alert('alertMe');},
// Log me.
logMe: function () {console.log('logMe');}
};