首页 > 代码库 > this指向

this指向

1.

function BigComputer(answer) {
this.the_answer = answer;
this.ask_question = function () {
console.log(this.the_answer); //undefined
console.log(document.getElementById("btn") === this); //true
}
}

function addHandler () {
var deep_thought = new BigComputer(42);
the_button = document.getElementById("btn");
the_button.onclick = deep_thought.ask_question;
}

window.onload = addHandler;

ask_question中的this指向了dom元素节点,而节点中不包含the_answer信息,所以结果为undefined

2. apply()与call()方法:改变this指向

this指向