这有什么好处:
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(){};
答案 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
属性,但您也无法从函数/对象中查找属性。