This Binding
this keyword에 대해 알아보자
var globalVar = 'something'; console.log(globalVar); console.log(window.ga); function foo(){ console.log('invoke'); function inFoo(){ console.log(this); //window } } window.foo();
function Person(name) { this.name = name; } Person.prototype.getName = function() { return this.name; } var me = new Person('Lee'); console.log(me.getName()); Person.prototype.name = 'Kim'; console.log(Person.prototype.getName());
// 객체 리터럴 방식 var foo = { name: 'foo', gender: 'male' } console.dir(foo); // 생성자 함수 방식 function Person(name, gender) { this.name = name; this.gender = gender; } var me = new Person('Lee', 'male'); console.dir(me); var you = new Person('Kim', 'female'); console.dir(you);
function Person(name) { this.name = name; // new 없이 호출하는 경우, 함수의 프로퍼티는 전역객체에 추가된다. }; // 일반 함수로서 호출되었기 때문에 객체를 암묵적으로 생성하여 반환하지 않는다. var me = Person('Kim'); console.log(me); // undefined console.log(window.name); // Kim, node.js인 경우에는 global.name
function ScopeSafeConstructorPattern(arg) { // 생성자 함수가 new 연산자와 함께 호출되면 함수의 선두에서 빈객체를 생성하고 this에 바인딩한다. // this가 호출된 함수(arguments.callee, 본 예제의 경우 A)의 인스턴스가 아니면 new 연산자를 사용하지 않은 것이므로 이 경우 new와 함께 생성자 함수를 호출하여 인스턴스를 반환한다. // arguments.callee는 호출된 함수의 이름을 나타낸다. 이 예제의 경우 A로 표기하여도 문제없이 동작하지만 특정함수의 이름과 의존성을 없애기 위해서 arguments.callee를 사용하는 것이 좋다. if (!(this instanceof arguments.callee)) { return new arguments.callee(arg); } // 프로퍼티 생성과 값의 할당 this.value = arg ? arg : 0; } var a = new A(100); var b = A(10); console.log(a.value); console.log(b.value);
Last updated