Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS add property to object via function call from construcator

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

like image 620
Noam Avatar asked Dec 19 '25 05:12

Noam


1 Answers

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

Sample

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
like image 98
Rajesh Avatar answered Dec 21 '25 08:12

Rajesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!