2

As shown below, the method() will output hello,undefined. What is the scope of the method()? Thank you.

var obj = {
    name:'Tom',
    sayHello:function() {
        console.log("hello," + this.name);
    }
}

obj.sayHello();

var method = obj.sayHello;
method();

output

hello,Tom
hello,undefined
0

4 Answers 4

3

Because method is part of the window object, this refers to window.

Consider this example

var name = 'foo';
method();

logs...

> hello,foo
Sign up to request clarification or add additional context in comments.

Comments

2

obj.sayHello()'s scope is within obj. method is a global property, so assigning it to the sayHello function makes the sayHello function look for this.name within the global scope.

To understand this, assign a global property of name directly in the script

var obj = {
    name:'Tom',
    sayHello:function() {
        console.log("hello," + this.name);
    }
}

obj.sayHello();

//Assign name to the global scope
this.name = "Jerry";
var method = obj.sayHello;

method.call(this); //Calling from the global scope, same as method()

//Then call method from the obj scope
method.call(obj);

Comments

2

The scope of method is the global window object

You'd have to do:

method.call(obj);  //instead of method()

or

var method = obj.sayHello.bind(obj);

to achieve the same efect

Info for the call method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

Info for the bind method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Cheers

Comments

1

var method's scope is global. it is equals to just define a function

var method = function() {
    console.log("hello," + this.name);
}

Comments

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.