[英]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.