使用js原型构建大型js应用程序的性能优势

时间:2016-01-29 13:56:21

标签: javascript inheritance prototype

这有什么好处:

HB.somepackage = HB.somepackage || {};

HB.somepackage.SomeGoodClass = function(someSelector){
    this.someSelector = someSelector;
}

HB.somepackage.SomeGoodClass.prototype.doSomeStuff = function(){
    var $obj = $(this.someSelector);
    // work your magic with $obj;
};

与此相反:

HB.somepackage = HB.somepackage || {};

HB.somepackage.someSelector = "HardCodedValueHere"; 
HB.somepackage.someOtherSelector = "AnotherHardCodedValueHere";

HB.somepackage.SomeReallyBadClass = function(){};

HB.somepackage.SomeReallyBadClass.prototype.doSomeStuff = function(){};

1 个答案:

答案 0 :(得分:1)

在这个问题中需要考虑很多。但是为了涵盖基础知识,它归结为prototypal inheritance和查找。

你的第一个例子:

HB.somepackage = HB.somepackage || {};

HB.somepackage.SomeGoodClass = function(someSelector){
    this.someSelector = someSelector;
}

HB.somepackage.SomeGoodClass.prototype.doSomeStuff = function(){
    var $obj = $(this.someSelector);
    // work your magic with $obj;
};

这使得someSelector成为SomeGoodClass的属性,可以根据被调用者进行更改。如果我要创建/调用绑定到不同上下文的函数,this.someSelector将对应于该被调用者上下文:

var newObject = {someSelector : 'oldSelector'};
HB.somepackage.SomeGoodClass.apply(newObject, 'newSelector');
newObject.someSelector; // 'newSelector'
HB.somepackage.SomeGoodClass.someSelector; // undefined

Codepen:http://codepen.io/anon/pen/yeENXj

所以在这里,您可能认为SomeGoodClass this.someSelector内部会引用SomeGoodClass.someSelector,但它没有。

在你的第二个例子中:

HB.somepackage = HB.somepackage || {};

HB.somepackage.someSelector = "HardCodedValueHere"; 
HB.somepackage.someOtherSelector = "AnotherHardCodedValueHere";

HB.somepackage.SomeReallyBadClass = function(){};

HB.somepackage.SomeReallyBadClass.prototype.doSomeStuff = function(){};

someSelector或多或少被用作需要在somepackage

的其他函数内引用的常量类型

根据您的应用程序的上下文和您希望/首选的编码实践,可能需要另一个。在第二个示例中,在apply()函数上调用call()SomeGoodClass显然不会更改"内部"类的someSelector属性,但您也无法从函数/对象中查找属性。