I am learning some jQuery basics with this great book: http://jqfundamentals.com/book/
There is an example that doesn’t return the right result.
Here is the code:
var myName = 'the global object',
sayHello = function () {
console.log('Hi! My name is ' + this.myName);
},
myObject = {
myName : 'Rebecca'
};
var myObjectHello = sayHello.bind(myObject);
sayHello(); // logs 'Hi! My name is the global object'
myObjectHello(); // logs 'Hi! My name is Rebecca'
The log returns undefined instead of the global object for sayHello(); and I’d like to know why…
It should work properly, unless you’ve wrapped that code in another function, creating a new variable scope.
Example: http://jsfiddle.net/RKYNn/
As such,
myNamewould not be available as a property on the global object.So if you did this:
…you’d get
undefinedbecausemyNameis no longer global, andthisin the function is a reference to the global object.