this(this的4种指向和改变this指向的方式)

  this是Javascript语言的一个关键字。

随着函数使用场合的不同,this的值会发生变化。但是有一个总的原则,那就是this指的是,调用函数的那个对象

1.this指向的形式4种

a.如果是一般函数,this指向全局对象window;

b.在严格模式下"use strict",为undefined.

c.对象的方法里调用,this指向调用该方法的对象.

d.构造函数里的this,指向创建出来的实例.

 

定义一个_this变量来存储this值,使全局对象里面的this 指向person 的this

this最近的函数是全局对象setTimeout

 
var person = {
name: "shafee",
age: 20,
say: function () { // 对象的属性是函数,就叫函数的方法
console.log(this.name); // object shafee
}
};
person.say();

var name = "Tom";
var body = document.getElementById("body");
body.onclick = function () {
console.log(this.name); // window Tom
}
var fn = person.say;
fn(); // window Tom
 
   

2. 改变this指向的方式

以下属于函数的方法

改变this的指向并且执行调用函数

.call(),  call(thisScope, arg1, arg2, arg3...)

.apply(), apply(thisScope, [arg1, arg2, arg3...]);两个参数

而bind 改变this的指向,返回的是函数

.bind()  bind(thisScope, arg1, arg2, arg3...)

call,可以传入多个参数,改变this指向后立刻调用函数

apply,可以传入数组

 bind改变this指向后,返回的是函数

----------------------------------------------------------------------

原文:https://www.jianshu.com/p/c415530030a9

原文地址:https://www.cnblogs.com/showcase/p/10488013.html