Skip to content

Instantly share code, notes, and snippets.

@pjchender
Last active August 8, 2018 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pjchender/3b8df37deff4dec882aa01b8d04d9d36 to your computer and use it in GitHub Desktop.
Save pjchender/3b8df37deff4dec882aa01b8d04d9d36 to your computer and use it in GitHub Desktop.
[AC] What is this?
let alphaPhoneX = {
name: 'AlphaPhoneX',
price: 14999,
features: ['long battery life', 'AI camera'],
showPhoneInfo: function () {
console.log('this now refers to', this)
console.log(`The price of ${this.name} is $${this.price}`)
}
}
// alphaPhoneX.showPhoneInfo() // 'this' now refers to 'alphaPhoneX'
const showAlphaPhoneXInfo = alphaPhoneX.showPhoneInfo
showAlphaPhoneXInfo()
let alphaPhoneX = {
name: 'AlphaPhoneX',
price: 14999,
features: ['long battery life', 'AI camera'],
showPhoneInfo: function () {
console.log('this now refers to', this)
console.log(`The price of ${this.name} is $${this.price}`)
const self = this
const showDetail = function () {
console.log('self now still refers to', self)
}
showDetail()
}
}
const showPhoneInfo = function (ram, storage) {
console.log(`The price of ${this.name} with ${ram}GB and ${storage}GM is $${this.price}, which has the newest features such as ${this.features.join(', ')}.`)
}
let alphaPhoneX = {
name: 'AlphaPhoneX',
price: 14999,
features: ['long battery life', 'AI camera'],
}
let alphaPhoneY = {
name: 'AlphaPhoneY',
price: 18900,
features: ['water proof', 'high screen resolution'],
}
// With .call()
// showPhoneInfo.call(alphaPhoneX, 3, 64)
// showPhoneInfo.call(alphaPhoneY, 6, 128)
// With .apply()
// showPhoneInfo.apply(alphaPhoneX, [3, 64])
// showPhoneInfo.apply(alphaPhoneY, [6, 128])
// With .bind()
const showPhoneInfoOfAlphaPhoneX = showPhoneInfo.bind(alphaPhoneX)
showPhoneInfoOfAlphaPhoneX(3, 64)
/**
* Implicit Binding - Situation 1
**/
let alphaPhoneX = {
name: 'AlphaPhoneX',
price: 14999,
features: ['long battery life', 'AI camera'],
showPhoneInfo: function() {
console.log(`The price of ${this.name} is $${this.price}, which has the newest features such as ${this.features.join(', ')}.`)
}
}
alphaPhoneX.showPhoneInfo()
/**
* Implicit Binding - Situation 2
**/
const showPhoneInfo = function () {
console.log(`The price of ${this.name} is $${this.price}, which has the newest features such as ${this.features.join(', ')}.`)
}
let alphaPhoneX = {
name: 'AlphaPhoneX',
price: 14999,
features: ['long battery life', 'AI camera'],
showPhoneInfo: showPhoneInfo,
similarPhone: {
name: 'AlphaPhoneY',
price: 18900,
features: ['water proof', 'high screen resolution'],
showPhoneInfo: showPhoneInfo,
}
}
alphaPhoneX.showPhoneInfo()
alphaPhoneX.similarPhone.showPhoneInfo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment