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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var obj = new Date(); | |
var todayDate = obj.getDate(); | |
console.log(todayDate); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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 |
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function C() { | |
this.a = 37; | |
} | |
var obj = new C(); | |
console.log(obj.a); // 37 |
Link 1 - new keyword
Link 2 - new keyword
Link 3 - new keyword
Link 4 - new keyword
No comments:
Post a Comment