var a = 1;
console.log(a); // 1
console.log(window.a); // 1
console.log(this.a); // 1
함수 vs 메서드
함수
는 그 자체로 독립적인 기능을 수행메서드
는 자신을 호출한 대상 객체에 관한 동작을 수행var func = function (x) {
console.log(this, x);
};
func(1); // Window { ... } 1
var obj = {
method: func
};
obj.method(2); // {method: f} 2
메서드
로 호출한 것임함수명 앞의 객체
이다.Function.prototype.call(thisArg[, arg1[, arg2[, ...]]])
var obj = {
a: 1,
method: function (x, y) {
console.log(this.a, x, y);
}
};
obj.method(2, 3); // 1 2 3
obj.method.call({ a: 4 }, 5, 6); // 4 5 6
Function.prototype.apply(thisArg[, argsArray])
유사배열객체에 배열 메서드를 적용
var obj = {
0: 'a',
1: 'b',
2: 'c',
length: 3
};
Array.prototype.push.call(obj, 'd');
console.log(obj); // {0: "a", 1: "b", 2: "c", 3: "d", length: 4}
var arr = Array.prototype.slice.call(obj);
console.log(arr); // ["a", "b", "c", "d"]
생성자 내부에서 다른 생성자 호출
function Person(name, gender) {
this.name = name;
this.gender = gender;
}
function Student(name, gender, school) {
Person.call(this, name, gender);
this.school = school;
}
function Employee(name, gender, company) {
Person.apply(this, [name, gender]);
this.company = company;
}
Function.prototype.bind(thisArg[, arg1[,arg2[, ...]]])
bound
접두어가 붙는다var func = function (a, b, c, d) {
console.log(this, a, b, c, d);
}
var bindFunc = func.bind({ x: 1 }, 4, 5);
console.log(func.name); // --- func
console.log(bindFunc.name); // bound func
상위 컨텍스트의 this를 내부함수나 콜백 함수에 전달하기
var objWithCall = {
outer: function () {
console.log(this); // - objWithCall
var innerFunc = function () {
console.log(this); // objWithCall
};
innerFunc.call(this);
}
};
objWithCall.outer();
var objWithBind = {
outer: function () {
console.log(this); // - objWithBind
var innerFunc = function () {
console.log(this); // objWithBind
}.bind(this);
innerFunc();
}
};
objWithBind.outer();
var report = {
sum: 0,
count: 0,
add: function () {
var args = Array.prototype.slice.call(arguments);
args.forEach(function (entry) {
this.sum += entry;
++this.count;
}, this); // 이처럼 마지막에 this를 넘겨준다.
},
average: function () {
return this.sum / this.count;
}
};
report.add(60, 85, 95);
console.log(report.sum, report.count, report.average()); // 240 3 80