JS中this和call

首先来了解一下JS中this的原理:

要访问自己的属性就必须使用 this.属性名

1.this总是指向它的直接调用者:

var a={
user:'Artimis',
fn:function(){
 console.log(this.user)
}
}

a.fn()  //Artimis => this指向a

var b=a.fn;
b()   //undefined => this指向window

2. 如果没有找到直接调用者,this就指向window
function fn(){
var user='Artimis';
console.log(this.user)
}
fn()   //undefined => this指向window

3.遇到return,如果返回的是对象,则this指向返回对象,否则指向函数function A(){
this.user='Artimis';
return {}   //return一个空对象
}

var a=new A();
console.log(a.user)  //undefined => this指向return的{}


function B(){
this.user='Artimis';
return 1   //return一个数值
}

var b=new B();
console.log(b.user)  //Artimis => this指向b

还有最后一种,就是当使用call,apply,bind绑定的时候,this就指向绑定对象

这里说一下call,apply以及bind的异同:
call和apply:相同点都是临时借用一个函数,并替换this为制定对象,不同点在于传参方式不一样,并且都是立即执行;
bind:基于现有函数,创建一个新函数,并且永久绑定this为其指定对象,可绑定参数,不过只是创建函数,不立刻执行。

举个例子:

//定义一个add 方法 function add(x, y) { return x + y; }
//用call 来调用 add 方法
function myAddCall(x, y) {
//调用 add 方法 的 call 方法
return add.call(this, x, y); }
//apply 来调用 add 方法
function myAddApply(x, y) {
//调用 add 方法 的 applly 方法
return add.apply(this, [x, y]);
}
console.log(myAddCall(10, 20));
//输出结果30
console.log(myAddApply(20, 20));
//输出结果40


从这里可以看出来call和appli都调用了add的方法,

还可以通过this改变作用域:

var name = '小王';

var obj = {name:'小李'};

function sayName() {
return this.name;
}

console.log(sayName.call(this)); //输出小白

console.log(sayName. call(obj)); //输入小红

this还能实现继承

function Animal(name){
this.name = name;
this.age = 15;
}

function Cat(name){
Animal.call(this, name);
this.catName = 'cat';
}

let o1 = new Cat('test1');
console.log(o1);
//Cat {name: "test1", age: 15, catName: "cat"}





原文地址:https://www.cnblogs.com/hzqzwl/p/11368542.html