console.log(this); // window
const obj = {
name: "waaaa",
greet() {
console.log(this.name); // "Alice"
}
};
obj.greet(); // "waaaa"
name: "waaaa",
arrr: [1,2,3,4],
greet() {
console.log(this.name); // "Alice"
}
checkthis() {
this.arr.forEach(function showThis() {
console.log(this);
})
}
}
checkthis(); // 브라우저에서는 Window, strict 모드에서는 undefined
function Person(name) {
this.name = name;
}
const alice = new Person("waaa");
console.log(alice.name); // "waaa"
화살표 함수에서는 this가 렉시컬 컨텍스트를 따릅니다.
const obj = {
name: "waaa",
greet: () => {
console.log(this.name);
}
};
obj.greet(); // undefined (렉시컬 컨텍스트로 인해 this는 Window를 참조)
지정된 파라미터를 갖는 함수를 정의함.
주요 코드 흐름 중간에 독자적인 구문 형태로 존재.
function functionName() {
console.log("Can Hoisting");
}
호이스팅 가능. 선언 전에도 호출 가능.
표현식이나 구문구성 내부에 생성됨. (주로 할당 표현식 '=' 우측에)
클로저로 사용하거나 콜백으로 사용할 수 있다.
var functionName = function() {
console.name("Can NOT Hoisting");
}
호이스팅 불가. 에러발생.
실행 흐름이 해당 함수에 도달했을 때 함수가 생성됨.
정의와 동시에 실행되는 함수.
(function() {
console.log("I am an IIFE!");
})();
const obj = {
greet(name) {
return `Hello, ${name}!`;
}
};
console.log(obj.greet("waaaaa")); // "Hello, waaaaa!"
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, ${this.name}!`;
}
}
const alice = new Person("wjjjjj");
console.log(alice.greet()); // "Hello, wjjjjj!"