this 改变this的指向

16次阅读

共计 1826 个字符,预计需要花费 5 分钟才能阅读完成。

this 是 Javascript 语言的一个关键字。
它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。比如,
function test() {
this.x = 1;
}

this 是当前执行上下文中的一部分。
this 永远指向函数的调用者。随着函数使用场合的不同,this 的值会发生变化。但是有一个总的原则,那就是 this 指的是,调用函数的那个对象。
1.this 指向的形式 4 种
a. 如果是一般函数,this 指向全局对象 window;
b. 在严格模式下 ”use strict”, 为 undefined.
c. 对象的方法里调用,this 指向调用该方法的对象.
d. 构造函数里的 this, 指向创建出来的实例.
e. 在事件处理函数中,this 指向触发事件的 DOM 对象
//a
function bar() {
console.log(this);// 一般函数,this 指向全局对象 window
}
bar();

//b
var foo = function() {
“use strict”;
console.log(this);// 表示使用严格模式; 在严格模式下, 为 undefined
}
foo();

//c
var name = ‘tesla’;
var car = {
name:”bmw”,
drive: function() {
console.log(this); //object car
console.log(this.name); //bmw

var that = this;// 定义一个 that 变量来存储 this 的值

setTimeout(function(){//setTimeout 是全局函数
console.log(this); //window
console.log(this.name); //tesla

console.log(that); //object car
console.log(that.name); //bmw
},1000);
}
}
car.drive();

//d
var name = ‘tom’;
// 声明一个函数
function person() {
console.log(arguments.length);
this.name = arguments[0];
this.age = arguments[1];
console.log(this);
console.log(this.name);
console.log(this.age);
}
person(); //0 window undefined undefined
var tom = new person(‘amy’,20); //2 person -> tom amy 20

//e
// 先遍历 ‘.tr-s’
$(‘.tr-s’).each(function (index,item) {
// 再遍历 ‘.tr-s’ 下的 ‘td-t’
$(this).find(‘.td-t’).each(function (index_s,item_s) {
//index_s 是下标
//item_s 是对应的对象
})
})

2. 改变 this 的指向
在 JS 中一切皆对象,函数也是对象,既然是对象就有属性和方法,在 JS 中所有的方法都有两个方法 call(),apply()
我们可以使用这两个方法来显示更改函数中 this 的指向,call、apply 这两个函数的共同特点:改变并立即执行。
区别就是传参方式不同 call 是一个一个传入 apply 是传入一个数组,一次性传完。
.call(), call(thisScope, arg1, arg2, arg3…)
.apply(), apply(thisScope, [arg1, arg2, arg3…]); 两个参数
在 ES5 中新增了 bind(), 该方法也是强制更改 this 指向
而 bind 改变 this 的指向,返回的是函数
.bind() bind(thisScope, arg1, arg2, arg3…)
但是 bind 和 call、apply 的区别是 bind 更改 this 后不会立即执行,它会返回一个新函数。
bind 传参也是一个一个的传入
var obj = {
name:’tom’,
age:20
}

function show(a,b){
console.log(a,b);
}

// 独立调用
show(1,2);

// 强制更改 this 指向为 obj 并立即执行该函数
show.call(obj,1,2);
show.apply(obj,[1,2]);

// 强制更改 this 指向 obj, 不会立即执行, 它会返回一个新函数, 需要主动去执行这个函数
show.bind(obj,1,2)();

正文完
 0