美文网首页JS
JS中this的指向和改变this指向

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

作者: HunterHu | 来源:发表于2017-06-26 22:04 被阅读0次

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();

相关文章

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

    this的指向 1.直接调用,指向window 2.在函数里调用,指向window 3.在构造函数里用new调用,...

  • JS中的this指向及改变this指向

    this是包含它的函数作为方法被调用时所属的对象。说明:这句话有点咬嘴,但一个多余的字也没有,定义非常准确,我们可...

  • 面试题集

    简述JS中this的指向和如何改变它的指向 javascript中,this是动态绑定的,它可以是全局对象、当前对...

  • js中this问题小结

    在使用js中的this时,由于js的语法规则,this的指向是会改变的,js中的this指向是根据函数在执行时的作...

  • this的指向和改变this的指向

    一、this的指向 普通函数调用 function fn(){ console.log(this) //thi...

  • JS中----this的指向和如何修改this的指向

    this this是js中的一个关键字,函数运行时自动生成的一个内部对象,只能在函数内部使用。我们要讨论的是 th...

  • JS进阶篇-this指向问题

    JS中this的指向问题不同于其他语言,JS中的this不是指向定义它的位置,而是在哪里调用它就指向哪里。 JS中...

  • JS中this指向

    一、全局作用域中的thises5与es6中严格模式与非严格模式全局函数的this都指向window 二、全局作用域...

  • JS中this指向

    函数有4种调用方式,对应就有4种绑定规则:默认绑定、隐式绑定、硬绑定和构造函数绑定。 1、默认绑定 当作为普通函数...

  • js中this指向

    1.this总是指向函数的直接调用者2.如果有new关键字,this指向new出来的那个对象3.DOM事件中thi...

网友评论

    本文标题:JS中this的指向和改变this指向

    本文链接:https://www.haomeiwen.com/subject/hxxscxtx.html