Passing javascript object property
How do you go about passing an objects properties in the follwoing situation:
ObjectTest = function()
{
this.var1= "3";
this.var2= "";
}
and the call
ObjectTest .prototype.allFriends = function() {
function bindEvents() {
//pass var1 here
}
}
Is 开发者_StackOverflow中文版there a way to pass the ObjectTest properties without passing them as properties of the bindEvents(). I'd prefer a global solution if at all possible
You use the same code in the prototype of allFriends as you used in the constructor:
ObjectTest = function()
{
this.var1= "3";
this.var2= "";
}
ObjectTest.prototype.allFriends = function() {
alert(this.var1);
}
It's the same: this.var1 - run this:
ObjectTest = function() {
this.var1 = 3;
this.var2 = "";
};
ObjectTest.prototype.allFriends = function() {
alert(this.var1);
};
x = new ObjectTest();
x.allFriends();
Or see this fiddle: http://jsfiddle.net/9XYZU/
ObjectTest.prototype.allFriends = function() {
do_smth_with(this.var1);
}
Beware, though, that you create a new ObjectTest
by calling new ObjectTest()
; without the new
keyword it will not work.
EDIT: It will still work, because of the inner function will inherit the outer function's (allFriends
) scope:
ObjectTest .prototype.allFriends = function() {
function bindEvents() {
console.log(this.var1);
}
}
If it still doesn't work for you, use a reference to the parent's this
:
ObjectTest .prototype.allFriends = function() {
var parent = this;
function bindEvents() {
console.log(parent.var1);
}
}
精彩评论