Keywords JavaScript this

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

    In JavaScript, in most object-oriented programming languages, this is a special keyword, it is used in the method to transfer refers to the method called object. The value of this can be composed of a series of simple steps to determine.

// Use the Function.call () method call

 

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.call( secondObject ); // "Hi! My name is Colin"

 

// Use the Function.bind () method call

 

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"

 

// Method of connecting to the 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"

    When the call is hidden in a namespace in, often want the method reference is stored in a variable in order to reduce the amount of code input. It is important, not so for instance methods. Because that will result in a method in the this value changes, resulting in incorrect code operation.

 

var myNamespace = {

myObject: {

sayHello: function() {

console.log( "Hi! My name is " + this.myName );

},

myName: "Rebecca"

}

};

 

var hello = myNamespace.myObject.sayHello;

 

hello(); // "Hi! My name is undefined"

    However, you can be such a safe method call.

var myNamespace = {

myObject: {

sayHello: function() {

console.log( "Hi! My name is " + this.myName );

},

myName: "Rebecca"

}

};

 

var obj = myNamespace.myObject;

 

obj.sayHello(); // "Hi! My name is Rebecca"

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Bert at November 15, 2013 - 6:09 AM