this
Use of keywords
Using in JavaScriptthis
The keyword represents the object that invokes the method, which is the same as most object-oriented languages. But becausecall
、apply
、bind
The effects of such functions, we can changethis
The object being referred to.
- using
call
or apply
function called, this
refers to the first parameter passed in the object, if the incoming null
or undefined
, which represents the global object (window
).
- Calls a function (method) through an object that represents the object in the function that
this
called the function.
- Represents a global object in a function that is called alone
this
.
var MyObject = { SayHello: function() { Console.Log("Hi, my name is" + This.MyName); }, MyName: "Rebecca"};var Secondobject = { MyName: "Colin"};MyObject.SayHello(); //"Hi, my name is Rebecca"MyObject.SayHello.Pager(Secondobject); //"Hi, my name is Colin"
var MyName = "The Global object";var SayHello = function() { Console.Log("Hi, my name is" + This.MyName);};var MyObject = { MyName = "Rebecca"};var Myobjecthello = SayHello.Bind(MyObject);SayHello(); //"Hi, my name is the global object"Myobjecthello(); //"Hi, my name is Rebecca"
JavaScript can dynamically add functions to objects in the run, which will also result in this
changes to the surrogate object.
var MyName = "The Global object";var SayHello = function() { Console.Log("Hi, my name is" + This.MyName);};var MyObject = { MyName: "Rebecca"};var Secondobject = { MyName: "Colin"};MyObject.SayHello = SayHello;Secondobject.SayHello = SayHello;SayHello(); //"Hi, my name is the global object"MyObject.SayHello(); //"Hi, my name is Rebecca"Secondobject.SayHello(); //"Hi, my name is Colin"
Also, you cannot directly add a short reference to a function that is in a darker namespace, causing this
it to become a global object, but you can set a short reference to the object it is located in.
var MyNamespace = { MyObject: { SayHello: function() { Console.Log("Hi, my name is" + This.name); }, MyName: "Rebecca" }};var Hello = MyNamespace.MyObject.SayHello;Hello(); //"Hi, my name is undefined"var obj = MyNamespace.MyObject;obj.SayHello(); //"Hi, my name is Rebecca"
Tips
< Code style= "font-family: ' Ubuntu mono ', Consolas, ' Liberation Mono ', courier,monospace; Font-size:1em; padding:2px 5px ">call with apply
is that apply
receives two parameters: this
and an array of arguments to the function, while call
is this
, but is followed by the argument list of the function.
This document is organized by the Changsha Camp David Education .
jquery lesson Fourth The use of this in JavaScript