RcBuilder@walla.com
call centre: 054-5614020

javascript fixing the ‘new’ keyword

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

javascript fixing the lack of ‘new’ keyword when creating an instance of an object

when creating an instance of the object and forget to use the ‘new’ keyword
the ‘this’ variable will refer to the ‘window’ object.
we can use this behavior to initialize a fresh instance of the current object and return it.
this way we’ll be able to fix the issue and it would work the same as
if we used the ‘new’ keyword.

e.g:
function Person() {
if(this === window) // someone forget to use the ‘new’ keyword
return new Person();

this.firstName = ‘Roby’;
this.lastName = ‘Cohen’;
this.sayYourName = function () {
return this.firstName + ‘ ‘ + this.lastName;
}
}

var person = Person(); // issue fixed by the Person constructor
var person2 = new Person(); // ok

 

Author Avatar

About the Author

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

No Comments


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