3

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

1
  • 5
    The value of this is set based on how a function is called. If you call a function as a property of an object, this in the function becomes the object. Commented Jun 26, 2016 at 12:17

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

@Downvoter, please find updates and if something is missing or incorrect, please point it out.
Got it. Thank you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.