以下是添加我需要的方法的三个选项 原型。我想知道是否有任何问题 任何这些模式。使用这样的原型是否有所不同,或者它们只是以不同的方式编写它们。
每次选项运行后,我都可以拨打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;
// 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');}
};