在优化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,或者我可以在主构造函数体中声明我的因变量。
但我想知道,就业绩而言,实现这一目标的最佳方式是什么?
谢谢
发布于 2013-07-30 05:51:43
要在创建toWhom时引用person,可以将值存储在单独的变量中:
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的实例。
https://stackoverflow.com/questions/17939012
复制相似问题