const dog = {
name: 'Nurung',
sayName: function() {
console.log(this.name); //누렁이
function sayId() {
console.log(this); // window
}
sayId();
}
}
dog.sayName(); //누렁이 window
'use strict';
console.log(this === window); // true
const dog = {
name: 'Nurung',
sayName: function() {
console.log(this.name);
}
dog.sayName(); //누렁이
'use strict'
function getThis() {
return this;
}
console.log(getThis()); //undefined
function getThis() {
return this;
}
console.log(getThis()); //window
function logThis() {
"use strict";
console.log(this);
}
[1, 2, 3].forEach(logThis); // undefined, undefined, undefined
setTimeout(logThis, 1000); // undefined
[1, 2, 3].forEach(logThis, { name: "obj" });
// { name: 'obj' }, { name: 'obj' }, { name: 'obj' }
const globalObject = this;
const foo = () => this;
console.log(foo() === globalObject); // true
const obj = { name: "obj" };
console.log(foo.call(obj) === globalObject); // true
const boundFoo = foo.bind(obj);
console.log(boundFoo() === globalObject); // true
var obj = {
bar: function() {
var x = (() => this);
return x;
}
};
var fn = obj.bar();
console.log(fn() === obj); // true
var fn2 = obj.bar;
console.log(fn2()() == window); // true
function Person(name) {
this.name = name;
}
var nurung = new Person('nurung');
console.log(nurung.name); //누렁이
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
function sum() {
return this.a + this.b + this.c;
}
var o = {
a: 1,
b: 2,
c: 3,
get average() {
return (this.a + this.b + this.c) / 3;
}
};
Object.defineProperty(o, 'sum', {
get: sum, enumerable: true, configurable: true});
console.log(o.average, o.sum); // 2, 6
* 접근 또는, 설정하는 함수에서 this가 결정됨, 이 경우 o.sum이 가리키는 this는 o가 됨
function bluify(e) {
this.style.backgroundColor = "#A5D9F3";
}
const elements = document.getElementsByTagName("*");
for (const element of elements) {
element.addEventListener("click", bluify, false);
}
<button onclick="alert(this.tagName.toLowerCase());"></button>
<button onclick="alert((function() { return this; })());"></button>
출처:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/this
https://nykim.work/71