javascript - 私有(private)的、基于实例的、高效的函数 |所需执行时间

标签 javascript

JavaScript 语言不直接支持类或基于类的继承。

但是,在 JavaScript 中有许多类的实现。

我见过的所有实现都需要使用自调用函数来创建私有(private)的、基于实例的高效函数。

函数有隐私

var foo = function(){ /* private to foo here */ };

但如果您基于它制作原型(prototype),您现在就有了公共(public)的、基于实例的、高效的成员。

foo.prototype.func = function(){ /* private to func */ }; // foo.func in public now.

如果你像这样在 foo 中放置一个函数

var foo = function() { 
    var funcInner = function(){}; 
}; // funcInner is now re-defined in each call to foo.  In-efficient.

你得到了缺失的隐私,但现在效率低下。

因此,拥有私有(private)的、基于实例的、高效的函数的唯一方法是使用模块模式(或类似的自调用模式)

    var NS = (function(){ 
    var private = function(){ /* code */ }; // only created once b.c. in module pattern.
    var publik = {};
        publik.funcPublic = function(){ /* code */ };
    return publik;
})();

通话

NS.funcPublic();

由此看来,要拥有私有(private)的、基于实例的、高效的函数,少量的执行时间是必要的吗?

这是正确的吗?

最佳答案

您介绍的模块模式不是一个好的解决方案。它返回一个对象 publik,但您很可能想模拟一个类,对吗?所以我猜您打算使用 new 运算符来创建 publik 类型的新实例。这不适用于对象,因此您需要在想要创建新实例时调用此匿名函数 - 最终每个实例都有一个新的私有(private)函数。 (不知道这是否可以理解,请问是否需要说明!)

我必须提供一个在现实中非常有效的解决方案:

var Car = (function() {
    // Private functions as local variables:
    var privateFunc = function(self) {};        

    // Create a local variable that will be the class (a function, to
    // enable the "new" keyword.
    var Car = function() {};

    // Attach public methods to the prototype! That's the most efficient way.
    Car.prototype.publicFunc = function() {
        privateFunc(this); // the private functions needs probably
                           // to know about the current instance
    };

    // Now return only the completed "class", to get it out into the wild
    return Car;
})();

var bmw = new Car();
bmw.publicFunc();

关于javascript - 私有(private)的、基于实例的、高效的函数 |所需执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11917246/

相关文章:

javascript - 以编程方式选择一个选项 - Materialize css

javascript - 将 Javascript 转换为 ASP.NET 中的代码隐藏

javascript - 将 ng-class 绑定(bind)到自定义 AngularJS 指令中的本地范围表达式

javascript - 处理路由时出错 : Cannot read property 'connectOutlet' in Ember. js

javascript - webrtc pc.onaddstream window.URL.createObjectURl 远程视频未显示

javascript - "Uncaught TypeError: Cannot read property ' 添加事件监听器 ' of null"

javascript - JavaScript 变量可以输入吗?

javascript - JSLint 类型混淆 : function and object with jQuery . css()

javascript - scrollTop offset() 无法在容器内使用 div 进行动画处理/正常工作

javascript - 停止 Google Maps API v3 中的空闲事件