[英]What is the best way to define a javascript object with methods and properties? (if its possible in a native way)
[英]What is the best way to define dependent variables in an object?
在Google開發人員關於優化JavaScript代碼的建議中,他們提到為對象聲明/初始化新變量的最佳方法是使用原型。 例如,代替:
foo.Bar = function() {
this.prop1_ = 4;
this.prop2_ = true;
this.prop3_ = [];
this.prop4_ = 'blah';
};
采用:
foo.Bar = function() {
this.prop3_ = [];
};
foo.Bar.prototype.prop1_ = 4;
foo.Bar.prototype.prop2_ = true;
foo.Bar.prototype.prop4_ = 'blah';
但是,就我而言,我在變量之間有一個依賴關系,例如:
var appv2 = function(){
this.start(this.person, this.car);
};
appv2.prototype.toWhom = 'Mohamed';
appv2.prototype.person = new person(this.toWhom);
appv2.prototype.car = new car();
appv2.prototype.start = function(person, car){
console.log('start for appv2 is called');
person.sayHello('me app v2');
car.brand();
};
new appv2();
在主要構造函數主體或對象的方法函數之外使用this.toWhom將產生未定義的結果。 為了解決這個問題,我可以使用appv2.prototype.toWhom而不是this.toWhom,或者可以在主構造函數主體中聲明我的因變量。
但是我想知道在性能方面最好的方法是什么?
謝謝
要在創建person
引用toWhom
,可以將值存儲在單獨的變量中:
var toWhom = appv2.prototype.toWhom = 'Mohamed';
appv2.prototype.person = new person(toWhom);
或者,您懷疑從prototype
引用了它:
appv2.prototype.person = new person(appv2.prototype.toWhom);
this.toWhom
之所以undefined
是因為this
沒有引用appv2
的實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.