gpt4 book ai didi

javascript - 使用 constructor.prototype 方法创建 JavaScript 库

转载 作者:行者123 更新时间:2023-11-29 21:58:45 25 4
gpt4 key购买 nike

我正在研究用于制作 JavaScript 库的系统。我已经看到大多数库使用诸如 "Immediately Invoked Function Expression" 之类的方法。 .这种方法对我来说使代码非常难读。

我想知道使用这种方法有什么好处?

使用基本的 .prototype 系统创建库有哪些限制?

例如,使用此模式创建库有什么问题?:

function Library(){

this.property = 'val';

}

Library.prototype.method = function(){
// a method
}

//and to use the library
var lib = new Library();

最佳答案

立即执行的函数本质上只是一种避免使用应该私有(private)的变量污染全局范围的方法。

您的方法很好,但是如果您希望您的库在内部引用不应属于您的公共(public) API 的私有(private)数据怎么办?示例:

var Some_class = (function() {

var foobar = 'foo'; //private; library can read it but public API can't

var api = function() { /* constructor */ };
api.prototype.method = function() { return foobar == 'foo' ? 1 : 0; }

return api;

})();

var instance = new Some_class();
instance.method();

foobar 是供您的图书馆使用的私有(private)(即内部)变量,但不能通过其 API 公开访问。

关于javascript - 使用 constructor.prototype 方法创建 JavaScript 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25035011/

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