Skip to content

Instantly share code, notes, and snippets.

@yoelfme
Created September 23, 2016 07:04
Show Gist options
  • Select an option

  • Save yoelfme/8a5300ea0f006e001c458f67c594f24e to your computer and use it in GitHub Desktop.

Select an option

Save yoelfme/8a5300ea0f006e001c458f67c594f24e to your computer and use it in GitHub Desktop.
How to function this keyword in Javascript
/*
- Implicit Binding
- Explicit Binding
- new Binding
- window Binding
*/
// Implicit Binding
// Left of the Dot at Call Time
var Person = function (name, age) {
return {
name: name,
age: age,
sayName: function () {
console.log(this.name)
},
mother: {
name: 'Stacey',
sayName: function () {
console.log(this.name)
}
}
}
}
var jim = Person('Jim', 42)
jim.sayName()
jim.mother.sayName()
// Explicit Binding
// call, apply, bind
var sayName = function (lang1, lang2, lang3) {
console.log('My name is ' + this.name + ' and I know ' + lang1 + ', ' + lang2 + ', and ' + lang3)
}
var stacey = {
name: 'Stacey',
age: 34
}
var languages = ['JavaScript', 'Ruby', 'Python']
sayName.call(stacey, languages[0], languages[1], languages[2])
sayName.apply(stacey, languages)
var newSayName = sayName.bind(stacey, languages[0], languages[1], languages[2])
newSayName()
// new Binding
var Animal = function (color, name, type) {
this.color = color;
this.name = name;
this.type = type;
}
var zebra = new Animal('black and white', 'Zorro', 'Zebra')
console.log(zebra)
// windod Binding
var sayAge = function () {
console.log(this.age)
}
sayAge()
window.age = 30
sayAge()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment