The reason to use JS .call() method?

后端 未结 4 1300
小鲜肉
小鲜肉 2020-11-30 19:33

I\'m interested what\'s the reason to have call() method in JS. It seems it duplicates usual method of calling this.

For example, I have a code with cal

4条回答
  •  一整个雨季
    2020-11-30 20:06

    2017 Update

    All functions by way of Function.prototype have the .call method. The reason to use .call() is to specify what the variable "this" refers to.

    MDN specifies:

    The call() method calls a function with a given this value and arguments provided individually.

    Consider the following:

    function x() {
        return this;
    }
    
    x()
    

    In strict mode x() returns undefined in non strict mode it returns the Global object, Window in a browser context.

    Example with .call() we tell it what "this" refers to:

    function x() {
        return this;
    }
    
    var obj = {
        myName      : 'Robert',
        myLocation  : 'Earth'
    }
    
    x.call(obj);
    

    Result: {myName: "Robert", myLocation: "Earth"}. In the above example we are specifying the obj object as the value of this inside the function x()

    It can be used to emulate inheritance in OOP.

    Example:

    var Robert = {
        name: "Robert Rocha",
        age: 12,
        height: "5,1",
        sex: "male",
        describe: function() {
            return "This is me " + this.name + " " + this.age + " " + this.height + " " + this.sex;
        }
    };
    

    Lets say that the above is a master object(prototype) and you want to inherit the function describe in another object:

    var Richard = {
        name: "Richard Sash",
        age: 25,
        height: "6,4",
        sex: "male",
    }
    

    The Richard object does not have the describe function and you want to simply inherit ,so to speak, the function. You would do it like so:

    console.log( Robert.describe.call( Richard ) );
    

    Output: This is me Richard Sash 25 6,4 male

提交回复
热议问题