Skip to content

Instantly share code, notes, and snippets.

@kavitshah8
Last active September 28, 2015 15:53
Show Gist options
  • Save kavitshah8/61c7356a79ebcb59146d to your computer and use it in GitHub Desktop.
Save kavitshah8/61c7356a79ebcb59146d to your computer and use it in GitHub Desktop.
scope and this
name = 'Kavit';
var team = {
name: 'Kevin',
member: {
name: 'Nik',
getName: function () {
return this.name;
}
}
};
// In JavaScript context of this depends on how a function is invoked, not how it’s defined.
console.log( team.member.getName() );
var test = team.member.getName;
console.log( test() ); // returns Kavit in browser, but returns undefined in node environment
console.log( test.call( team.member ) );
// Print Kevin
// Without modifying this function in any way, how can you execute it in such a way where
// it will output “Joe is hungry”
function speak () {
var reply = [ this.person, 'is', this.feeling].join(' ');
console.log( reply );
}
var i = { person: 'Joe', feeling: 'hungry' };
var o = {
f: function() {
return this.a + this.b;
}
};
var p = Object.create(o);
p.a = 1;
p.b = 4;
console.log(p.f()); // 5
// global object browser, window . Not using var makes them global
// Variables has function scope
(function(){
var a = 5;
b = 5;
})();
console.log(b); // 5
console.log(a); // undefined
// foo = 'cracks';
var myObject = {
foo: "bar",
func: function() {
var self = this;
console.log("outer func: this.foo = " + this.foo);
console.log("outer func: self.foo = " + self.foo);
(function() {
console.log("inner func: this.foo = " + this.foo);
console.log("inner func: self.foo = " + self.foo);
}());
}
};
myObject.func();
// The above code will output the following to the console:
// outer func: this.foo = bar
// outer func: self.foo = bar
// inner func: this.foo = undefined
// inner func: self.foo = bar
// In the outer function,
// both this and self refer to myObject and therefore both can properly reference and access foo.
// In the inner function, though,
// this no longer refers to myObject. As a result, this.foo is undefined in the inner function,
// whereas the reference to the local variable self remains in scope and is accessible there.
// (Prior to ECMA 5, this in the inner function would refer to the global window object;
// whereas, as of ECMA 5, this in the inner function would be undefined.)
m
name = 'Kavit';
var team = {
name: 'Kevin',
member: {
name: 'Nik',
getName: function () {
return this.name;
}
}
};
// In JavaScript context of this depends on how a function is invoked, not how it’s defined.
console.log( team.member.getName() );
var test = team.member.getName;
console.log( test() ); // returns Kavit in browser, but returns undefined in node environment
console.log( test.call( team.member ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment