JavaScript中this指向问题和改变this指向方法

JavaScript中this指向问题和改变this指向方法

一. 各种情况下this的指向

  1. 普通函数调用时this指向window
function fn() {
       console.log(this);
}
fn();  //window
  1. 构造函数调用时this指向实例化对象,原型对象里this也指向实例化对象
        function Star(name, age) {
            this.name = name;
            this.age = age;
            console.log(this);
        }
        var star = new Star('jisoo', 25);  //Star {name: "jisoo", age: 25}
  1. 对象方法调用时this指向该方法的所属对象
        var obj = {
            name: 'jisoo',
            age: 25,
            fn: function() {
                console.log(this);
            }
        }
        obj.fn();  //Star {name: "jisoo", age: 25}
  1. 事件绑定方法的this指向绑定事件对象
        var btn = document.querySelector('button');
        btn.addEventListener('click', function() {
            console.log(this);
        })  //<button>点击<button>
  1. 定时器函数的this指向window
  2. 立即执行函数的this指向window

二. 改变this的指向

  1. apply()方法
    apply()的作用:能劫持另外一个对象的方法,继承另外一个对象的属性.
    function.apply(obj,args)方法接收两个参数:
    obj:这个对象将代替function里的this对象
    args:数组,它将作为参数传给function(args–>arguments)
//首先定义一个Star对象
        function Star(name, age) {
            this.name = name;
            this.age = age;
        }
//在定义一个歌手对象
        function Singer(name, age, song) {
            Star.apply(this, arguments);
            this.song = song;
        }
        var singer = new Singer('张韶涵', 39, '隐形的翅膀');
        console.log(singer.name);//'张韶涵'
        console.log(singer.age);//39
        console.log(singer.song);//‘隐形的翅膀’

我们可以看出,在歌手这个对象里并没有写this.name=name;this.age=age,但是最后singer.name,singer.age都打印出来了,这就是apply()的作用
分析Star.apply(this, arguments)这行代码:
this:在创建对象在这个时候代表的是Singer
arguments:是一个数组,也就是[‘张韶涵’, 39, ‘隐形的翅膀’];
通俗一点讲就是:用Singer去执行Star这个类里面的内容,在Star这个类里面存在this.name等之类的语句,这样就将属性创建到了Singer对象里面
2. call()方法
call()的作用:能劫持另外一个对象的方法,继承另外一个对象的属性.
function.call(obj,[param1[,param2[,…[,paramN]]]])方法接收两个参数:
obj:这个对象将代替function类里this对象
params:这个是一个参数列表

        function Star(name, age) {
            this.name = name;
            this.age = age;
        }
        function Singer(name, age, song) {
            Star.call(this, name, age);
            this.song = song;
        }
        var singer = new Singer('张韶涵', 39, '隐形的翅膀');
        console.log(singer.name);
        console.log(singer.age);
        console.log(singer.song);

Star.apply(this, arguments);替换成Star.call(this, name, age);

猜你喜欢

转载自blog.csdn.net/Angela_Connie/article/details/110548350
今日推荐