我是一个 OO js 菜鸟,正在尝试以正确的方式创建一个新的 Javascript 库,但我很难理解如何最好地做到这一点并使其正常工作。我希望我的库能够自调用,以便对象 ABC
一旦 js 库文件包含在 html 中,就会实例化。但是,用户应该能够在 html 页面中调用该对象的方法。
我尝试了以下代码的几个不同版本,但似乎无法获得声明方法正常工作的原型(prototype)方法。在我的 HTML 页面上,我可以调用 ABC.alert();
并且它正确执行警报消息。但是,当我尝试调用ABC.alert2();
时它使用原型(prototype)继承,我知道这比仅仅在对象构造函数内部声明方法更具内存效率,但我似乎无法让它工作。我不断收到ABC.alert2 is not a function
。我确实看到我的 ABC 对象确实具有 proto 属性,但我似乎无法弄清楚如何使用原型(prototype)正确定义方法。是因为我使用的是自调用函数吗?我是否应该不使用自调用函数,而是在库的底部使用 var ABC = new defineABC();
手动创建对象的新实例?线?
还复制如下:
(function (window) {
'use strict';
function defineABC() {
var ABC = {};
ABC.alert = function() {
alert("hello this is working");
};
ABC.prototype.alert2 = function() {
alert("hello prototype is working inside constructor");
};
return ABC;
}
defineABC.prototype.alert3 = function() {
alert("hello prototype is working outside constructor");
};
if (typeof(ABC) === 'undefined') {
window.ABC = defineABC();
}
})(window);
ABC.alert(); //successful
ABC.alert2(); //fails
ABC.alert3(); //fails
最佳答案
您需要创建对象的实例才能使用原型(prototype)方法。
var abc = new defineABC()
abc.alert2();
abc.alert3();
所以你可以像这样在代码中定义它
if (typeof(ABC) === 'undefined') {
window.ABC = new defineABC();
}
最终的代码可能如下所示:
(function (window) {
'use strict';
function defineABC() {
}
defineABC.prototype.alert3 = function() {
alert("hello prototype is working outside constructor");
};
defineABC.prototype.alert = function() {
alert("hello this is working");
};
defineABC.prototype.alert2 = function() {
alert("hello prototype is working inside constructor");
};
if (typeof(ABC) === 'undefined') {
window.ABC = new defineABC();
}
})(window);
关于Javascript 库对象方法声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36990688/