Javascript This Called from Different Context
This will change its value when called from different context.
Consider the following codes:
var name = 'apple';
var obj = {
name: 'banana',
prop: {
name: 'melon',
getName: function () {
return this.name;
}
}
}
console.log(obj.prop.getName());
obj.getName = obj.prop.getName;
console.log(obj.getName());
var test = obj.prop.getName;
console.log(test());When accessing the function directly from an object, this will point to that object. But if the function is accessed differently (in the above example, assigned to a variable and then called), the context will be different.
// in browser environment
melon
banana
apple
// in node.js environment
melon
banana
undefined