Saturday, December 20, 2014

New Keyword in JavaScript

The new keyword create an instance of a user-defined object.
The new keyword create an instance of a built-in object types that has a constructor function.

Below program create an instance of a user-defined object.

function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
var person1 = new Person("Deepak", 24, "Male");
console.log(person1.name); // "Deepak"
console.log(person1.age); // 24
console.log(person1.sex); // "Male"
view raw gistfile1.js hosted with ❤ by GitHub
Below program create an instance of a built-in object types that has a constructor function.

var obj = new Date();
var todayDate = obj.getDate();
console.log(todayDate);
view raw gistfile1.js hosted with ❤ by GitHub
New operator takes a function constructor as a argument and create a new object which is extend from the prototype property of the function constructor and then execute the function constructor with the content of the newly created object and then return the newly created object.

/* this is not the real implementation of
new keyword this is only the basic implementation */
var myNew = function(fun){
var newObj = Object.create(fun.prototype);
fun.call(newObj);
return newObj;
};
view raw gistfile1.js hosted with ❤ by GitHub
/* this is not the real implementation of new
keyword this is only the basic implementation */
var myNew = function(fun){
var newObj = Object.create(fun.prototype);
fun.call(newObj);
return newObj;
};
function C() {
console.log(this); // C{}
this.a = 37;
}
var obj = myNew(C);
//var obj = new C();
console.log(obj); // C {a:37}
console.log(obj.a); // 37
view raw gistfile1.js hosted with ❤ by GitHub

this value with new keyword

When a function is used as a constructor (with the new keyword), its "this" is bound to new object being constructed.

function C() {
this.a = 37;
}
var obj = new C();
console.log(obj.a); // 37
view raw gistfile1.js hosted with ❤ by GitHub

Link 1 - new keyword
Link 2 - new keyword
Link 3 - new keyword
Link 4 - new keyword

No comments:

Post a Comment