[英]What is the best way to define dependent variables in an object?
In the Google developers recommendation for optimizing JavaScript code, they mention that the best way to declare/initialize new variables for object is to use the prototype. 在Google开发人员关于优化JavaScript代码的建议中,他们提到为对象声明/初始化新变量的最佳方法是使用原型。 For instance, instead of: 例如,代替:
foo.Bar = function() {
this.prop1_ = 4;
this.prop2_ = true;
this.prop3_ = [];
this.prop4_ = 'blah';
};
Use: 采用:
foo.Bar = function() {
this.prop3_ = [];
};
foo.Bar.prototype.prop1_ = 4;
foo.Bar.prototype.prop2_ = true;
foo.Bar.prototype.prop4_ = 'blah';
However, in my case I have a dependency between variables, for instance: 但是,就我而言,我在变量之间有一个依赖关系,例如:
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();
Using this.toWhom outside of the main constructor body or a method function of the object will yield undefined. 在主要构造函数主体或对象的方法函数之外使用this.toWhom将产生未定义的结果。 To solve this I could use appv2.prototype.toWhom instead of this.toWhom or I could declare my dependent variables inside of the main constructor body. 为了解决这个问题,我可以使用appv2.prototype.toWhom而不是this.toWhom,或者可以在主构造函数主体中声明我的因变量。
But I would like to know what is the best way, in terms of performance, to accomplish this? 但是我想知道在性能方面最好的方法是什么?
Thanks 谢谢
To reference toWhom
while creating person
, you can either store the value in a separate variable: 要在创建person
引用toWhom
,可以将值存储在单独的变量中:
var toWhom = appv2.prototype.toWhom = 'Mohamed';
appv2.prototype.person = new person(toWhom);
Or, reference it from the prototype
, as you suspected: 或者,您怀疑从prototype
引用了它:
appv2.prototype.person = new person(appv2.prototype.toWhom);
The reason this.toWhom
is undefined
is because this
doesn't refer to an instance of appv2
there. this.toWhom
之所以undefined
是因为this
没有引用appv2
的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.