Skip to content

Instantly share code, notes, and snippets.

@ysm-dev
Created August 3, 2019 15:20
Show Gist options
  • Select an option

  • Save ysm-dev/9b417f55eb7fee6e0ac7552c16d30c7d to your computer and use it in GitHub Desktop.

Select an option

Save ysm-dev/9b417f55eb7fee6e0ac7552c16d30c7d to your computer and use it in GitHub Desktop.
Markdium-๐Ÿ’ป ํ”„๋ก ํŠธ์—”๋“œ ๋ฉด์ ‘ ์งˆ๋ฌธ - JS #4
const Person = function(firstName) {
this.firstName = firstName;
this.sayName1 = function() { console.log(this.firstName); };
this.sayName2 = () => { console.log(this.firstName); };
};
const john = new Person('John');
const dave = new Person('Dave');
john.sayName1(); // John
john.sayName2(); // John
// ์ผ๋ฐ˜ ํ•จ์ˆ˜์˜ 'this'๊ฐ’์€ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ์ง€๋งŒ, ํ™”์‚ดํ‘œ ํ•จ์ˆ˜๋Š” ๋ณ€๊ฒฝํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.
john.sayName1.call(dave); // Dave (because "this" is now the dave object)
john.sayName2.call(dave); // John
john.sayName1.apply(dave); // Dave (because 'this' is now the dave object)
john.sayName2.apply(dave); // John
john.sayName1.bind(dave)(); // Dave (because 'this' is now the dave object)
john.sayName2.bind(dave)(); // John
var sayNameFromWindow1 = john.sayName1;
sayNameFromWindow1(); // undefined (because 'this' is now the window object)
var sayNameFromWindow2 = john.sayName2;
sayNameFromWindow2(); // John
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment