[英]how to access variables of parent object within function
我需要在原型中使用函數,這些函數可以訪問父對象變量,而無需在創建對象時執行。
var Foo=function(e,d) {
this.b=e;
this.c=d;
// this.d will be this.b + this.c
}
window.onload=function() {
var e=4,d=7;
var bas=new Foo(e,d);
// random things happen
Foo.prototype.addFunc=function() {
// want to create d (b + c), but can't access them
}();
console.log(bas.d); // should be 11
}
你不能像這樣調用原型的方法。 您只能在實例上調用該方法
var Foo=function(e,d) {
this.b=e;
this.c=d;
};
var e=4,d=7;
var bas=new Foo(e,d);
// random things happen
Foo.prototype.addFunc=function() {
this.d = this.b + this.c;
};
bas.addFunc();
alert(bas.d); // is 11
從技術上講,您可以像這樣調用函數...如果它返回一個函數本身,然后將其分配給原型。 但這肯定不是你想要的
要解決在一個語句中對所有實例調用addFunc的注釋:
要在所有實例上調用某個函數,您必須跟蹤所有實例。 這可以在Object定義(Foo構造函數)中完成。
要讓Object定義(構造函數)跟蹤它的所有實例有點復雜。
如果在函數中我創建了100個Foo實例並且函數退出,則這些實例將超出范圍。 但是因為Foo會跟蹤它的實例,它會引用這些實例,因此即使在函數退出后這些實例也不會被垃圾收集(超出范圍)。
要向Foo指示不再需要這些實例,您必須在實例上顯式調用destroy,以便不再在Foo._instances中保留對該實例的引用。
以下是一些演示代碼:
//Object definition of Foo (constructor function)
var Foo=function(e,d) {
this.b=e;
this.c=d;
//saving this instance in Foo._instances
this._instanceId=Foo._instanceCount;
Foo._instances[this._instanceId]=this;
Foo._instanceCount++;
}
//properties of the Object definition
Foo.allAddFunc=function(){
var thing;
for(thing in Foo._instances){
if(Foo._instances.hasOwnProperty(thing)){
Foo._instances[thing].addFunc();
}
}
};
//container for all instances of Foo
Foo._instances={};
//does not refllect the actual count
// used to create _instanceId
Foo._instanceCount=0;
//prototype of Foo (used for foo instances)
Foo.prototype.addFunc=function() {
this.d=this.b+this.c;
};
//when a Foo instance is no longer needed
// you should call destroy on it
Foo.prototype.destroy=function(){
delete Foo._instances[this._instanceId];
};
(function() {
var bas=new Array(10),i=0,len=bas.length;
//create instances
for(;i<len;i++){
bas[i]=new Foo(i,i*2);
};
//do something with all instances
Foo.allAddFunc();
//bas[] will go out of scope but all instances of
// Foo will stay in Foo_instances, have to explicitely
// destroy these instances
for(i=0,len=bas.length;i<len;i++){
console.log("bas.d at "+i+":",bas[i].d);
//Foo instance at bas[i] no longer needed
// destroy it
bas[i].destroy();
};
}());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.