What is the meaning of 'this'?

I am trying to understand the code below:

var MyModel = function (folders) { var thisType = this; this.callType = ko.computed({ read: function () { return "openLink"; }, owner: this }); 

Why set 'thisType' to 'this'?

Reading a document at http://knockoutjs.com/documentation/computedObservables.html

"Managing" this In case you are wondering what is the second parameter ko.computed (the bit in which we passed it in the previous code), which determines the value of this when evaluating the calculated observable. Without passing it, it would be impossible to refer to this.firstName () or this.lastName (). Experienced JavaScript encoders will find this obvious, but if you still know JavaScript, this may seem odd. (Languages ​​such as C # and Java never expect the programmer to set a value for this, but JavaScript does this because its functions themselves are not part of any object.)

Is 'this' a page object?

+4
source share
2 answers

I'm glad you asked this question. I like to think of myself as a pretty experienced js programmer, but I still did a double trick when I came across this in a js docs knockout.

Why install this type?

When you call an external function, you can still access the object this belongs to. Using closure, this is possible by storing this in a variable in the parent function.

The best example I can think of is the onclick event.

 <div id="test">content</div> document.getElementById("test").onclick = function(e){ var self = this; function test(){ alert(this); //[object Window] alert(self); //[object HTMLDivElement] } test(); }; 

Is 'this' a page object?

As other people have noted, there is a lot of documentation about this keyword.

+3
source

in js this refers to context execution

I like this excerpt from quirksmode.org :

In JavaScript, this always refers to the "owner" of the function that we are executing, or rather, the object that the function is. When we define our faithful doSomething () function on a page, its owner is the page, or rather, the window object (or global object) of JavaScript. The onclick property, however, belongs to the HTML element it belongs to.

Thus, in your example, this will have a MyModel context value at the time the instance was created.

+3
source

Source: https://habr.com/ru/post/1480463/


All Articles