RcBuilder@walla.com
call centre: 054-5614020

javascript that

26
Jan
2016
Posted by: RcBuilder  /   Category: class / function / JAVASCRIPT / Object / OOP / prototype   /   No Comments

javascript that

use local variable within a custom object to save reference to the current object
sometimes the ‘this’ variable not refer to the object contains the current function (callback calls, setTimeout etc.)
the best way to handle this is by save an extra reference to the actual object (it’s quite common to call it ‘that’)
declare it in the constractor!

syntax:

var that = this;

function Person(firstName, lastName) {
var that = this;

this.firstName = firstName;
this.lastName = lastName;

this.fun1 = function () {
setTimeout(function () {
console.log(‘fun1: ‘ + this.firstName + ‘ ‘ + this.lastName); // this refer to window!!
}, 100);
}

this.fun2 = function () {
setTimeout(function () {
console.log(‘fun2: ‘ + that.firstName + ‘ ‘ + that.lastName);
}, 500);
}
}

var person = new Person(‘Roby’, ‘Cohen’);
person.fun1(); // fun1: undefined undefined
person.fun2(); // fun2: Roby Cohen

Author Avatar

About the Author

בניית אתרים ופתרונות טכנולוגים | RcBuilder

No Comments


  • פיתוח מערכות
  • פתרונות טכנולוגים
  • קידום אתרים
  • בניית אתרים