this指向问题的几条规则
1.函数预编译过程this--------------------window
2.全局作用域里this------------- window
3.call/apply 可以改变函数运行时this指向
4.obj.func(); func()里面的this指向obj -----------------调用this指向谁、
5.new构造的函数 this代表的是函数体内部
例子1:
// 分别用con()运行和 new con()运行的结果
var num = 123;
function con() {
this.num = 234; //直接全局调用 this指向window 即window.num=234 此时num已经改变
console.log(num)
}
con() //234
var num1 = 123;
function con1() {
// var this=Object.create(con.prototype) new()的时候相当于在函数体创建了一个this对象里面放的就是原型链
this.num1 = 234;
console.log(num1) //123
console.log(this.num1) //234
}
new con1(); //123
例子2:
var a = 5;
function test() {
a = 0;
console.log(a); //0
console.log(this.a); //5
var a;
console.log(a); //0
}
test();
var a = 5;
function test() {
a = 0;
console.log(a); //0
console.log(this.a); //undefind
var a;
console.log(a); //0
}
new test();
例子3:
<script>
var name = '222';
var a = {
name: '111',
say: function () {
console.log(this.name);
}
}
var fun = a.say;
fun(); //222
a.say(); //111
var b = {
name: '333',
say: function (fun) { //
fun(); //执行 没有人调用 this还是指向window 3题还是222
}
}
b.say(a.say); //222
b.say = a.say;
b.say(); //333
</script>