Home javascript bind and this || JavaScript

bind and this || JavaScript [duplicate]

Author

Date

Category

There is a following code:

function greet () {
 Console.log ('Greet', this);
}
Let Person = {
 Name: "John",
 Sayhi: Greet,
 SayhiWindow: Greet.Bind (this)
}
person.sayhiwindow ()

The question arose: why when calling persons.sayhiwindow () in the console gives the object window, and not Person?


Answer 1, Authority 100%

It is worth remembering that the this is equal to the subject of the method of calling the method, if it is mentioned inside the method, in the body of the function, in its scope. When you specify SayhiWindow: greet.bind (this) , you assign the Sayhiwindow key value returned by the Greet.bind function (this) , and here this you use outside the body of the method, as an argument to call a function, and you are in a global area of ​​visibility, where this equals window .

What you are trying to achieve, you can implement this:

sayhiperson: function () {greet.bind (this) (); },

Answer 2, Authority 100%

Because in this place

sayhiwindow: greet.bind (this)

This is window , and person still does not exist ..

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions