Function.prototype.call() 绑定this指向

例子:bash

//绑定指向
    var obj3 = {}

    var login = function(){
        return this;
    };

    console.log(login() === window); //true
    console.log(login.call(obj3) === obj3); //true
复制代码

例子二:ui

var n = 123;
    var obj = {
        n: 456
    };

    function a() {
        console.log(this.n);
    }

    a.call() // 123
    a.call(null) // 123
    a.call(undefined) // 123
    a.call(window) // 123
    a.call(obj) // 456
复制代码

解析:this

var f = function () {
  return this;
};

f.call(5)
// Number {[[PrimitiveValue]]: 5}
复制代码

call的参数为5,不是对象,会被自动转成包装对象(Number的实例),绑定f内部的this

function add(a, b) {
  return a + b;
}

add.call(this, 1, 2) // 3
复制代码

除此以外,call还有一个很重要的用法(调用原生的方法)

var obj5 = {}
    alert(obj5.hasOwnProperty('toString')); //false

    obj5.hasOwnProperty = ()=>{
        return true;
    }

    console.log(obj5.hasOwnProperty('toString')); //true

    console.log(Object.prototype.hasOwnProperty.call(obj5,'toString')) //false
复制代码
相关文章
相关标签/搜索