I can't figure out why the following code:
function Foo() {
this.a = "a";
this.c = add();
}
var add = function() {
this.b = "added";
}
obj2 = new Foo();
alert("obj2.b is " + obj2.b); //obj2.b is Undefined
Won't create 'b' property to obj2 while this code:
function Foo() {
this.a = "a";
this.func1 = add;
this.c = this.func1();
}
var add = function() {
this.b = "added";
}
obj2 = new Foo();
alert("obj2.b is " + obj2.b); // obj2.b is added
Will create the 'b' property.
I'm new to JS, I tried reading about using function as constructor and basicly I got the idea but I guess there is still something I'm missing.
Thank you,
Noam
the value of this is determined by how a function is called.
If no caller, then this will point to default/global scope(window).
If you need to pass context to another function, you should use one of following: .apply, .bind
function Foo() {
this.a = "a";
this.c = add.apply(this);
}
var add = function() {
this.b = "added";
}
obj2 = new Foo();
console.log("obj2.b is " + obj2.b); //obj2.b is Undefined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With