JS

JS中this的指向和改变this指向

2017-06-26  本文已影响0人  HunterHu

this的指向

1.直接调用,指向window

var x=1;
console.log(this.x);
//输出 1

2.在函数里调用,指向window

var x=1;
function fn(num){
    var x=2;
    console.log(this.x);
}
fn();
//输出 1

3.在构造函数里用new调用,指向创建的新实例对象

function fn(){
    console.log(this);
}
let a=new fn();
//输出 {}(指向对象a)

4.在对象的方法里调用,指向调用它的对象

function fn(num){
    this.x=num;
    this.fn1=function(){
        console.log(this.x)
    }
}
let a=new fn(3);
a.fn1();
//输出 3

改变this的指向

1.用new调用函数,改变指向new的实例对象

function fn(){
    console.log(this);
}
let a=new fn();
//输出 {}(指向对象a)

2.bind

function fn(){
    console.log(this.name);
};
var obj={
    name:'jack',
};
var b=fn.bind(obj);
b();

3.call

function fn(name){
    this.name=name;
    this.fn1=function(){
        console.log(this.name);
    }
};
var obj={};
fn.call(obj,'jack');
console.log(obj.name);
obj.fn1();

4.apply

function fn(name,age){
    this.name=name;
    this.age=age;
    this.fn1=function(){
        console.log(this.name);
    }
};
var obj={};
fn.apply(obj,['jack',18]);
console.log(obj.age);
obj.fn1();
上一篇 下一篇

猜你喜欢

热点阅读