Tuesday, May 20, 2014

Javascript this

The "this" in javascript basically means the owner of the object which is executing the current code.

Global context
The code is executed in global context which owner is the window, so this === window.

Simple Function call
In strict mode, the value of this remains at whatever it's set to when entering the execution context. If it's not defined, it remains undefined.

As an object method If we change code a little,
t1.print = f1; which says t1 has a function which is pointing to function f1.
when run t1.print(), the this in f1 is the object t1 which is the owner of the object executing the function, so it returns "b".
You can see the owner is changed depending on how you call it.

call and apply
Using the call or apply methods allows you to specify what "this" is.
The main difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly
theFunction.apply(thisArg, arrayOfArgs)
theFunction.call(thisArg, arg1, arg2, ...)
If thisArg refers to an object, it’s set to the object the method is called on.
If thisArg is null, the function context is set to the global object, and the function behaves like a simple global function.But if the method is a function in strict mode, the actual value of null is passed in.

bind method
bind method is similar to call function. The difference is that bind return a function with "this" and args populated and call is actually executing the function.
Here is the source code of bind, actually it is a wrapper of apply


On the object's prototype chain
p inherits o. The code var p = Object.create(o); equals to the code below

refer to: http://2208326.blog.51cto.com/2198326/471627
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

No comments:

Post a Comment