A detailed introduction of call in js. What does this code block mean?


    function Animal() {
        this.name = "Animal";
        this.Say = function () {
            console.log(this);
            console.log(this.name);
        }
    }
    function Cat() {
        this.name = "Cat";
    }
    var animal = new Animal();
    var cat = new Cat();
    //animal.Say();
    animal.Say.call(cat);
  • is it? Calling this in animal.Say has been switched to point to the cat object, so console.log (this);
  • printed cat
  • console.log (this.name); printed cat

this call is so ignorant. What on earth is it? I really don"t know if you can give me an example or explain it to me, thank you

Mar.20,2021

call is the method used to specify the scope of a function. Call Function.prototype.call on the prototype chain of Function.

The first parameter of

call is the point of this. null/undefined may not be passed, and this points to window by default.

if you pass cat, then this will point to cat (object). You can also take the parameter


cat Animal <br>Animal

function Cat() {
    Animal.apply(this,arguments);
    this.name = "Cat";
}

so that all Cat instantiated objects inherit Animal.

Menu