// Code Starts
function Person(name) {
this.name = name;
console.log(this.name); //Output 1
console.log(this); //Output 2
}
var p1 = new Person("Object_Shashank");
var p2 = Person("Function_Shashank");
// Code Ends
p1 :
- Output 1: Object_Shashank
- Output 2: Person {name: "Object_Shashank"}
p2 :
- Output 1: Function_Shashank
- Output 2: Window {speechSynthesis: SpeechSynthesis, caches: CacheStorage, localStorage: Storage, sessionStorage: Storage, webkitStorageInfo: DeprecatedStorageInfo...}
Can someone please explain "p2: Output 2"
m87
4,5313 gold badges19 silver badges31 bronze badges
asked Feb 18, 2017 at 13:39
Shashank Shekhar
3513 silver badges11 bronze badges
1 Answer 1
It prints the window object because the this references the window object.
function Person(name){
this.name=name;
console.log(this.name); //Output 1
console.log(this); //Output 2 <-- this `this` will point to the object it belongs to , which in this case of p1 is Object_Shashank while for p2 is window
}
var p1=new Person("Object_Shashank");
var p2=Person("Function_Shashank"); // Equivalent to p2 = window.Person("Function_Shashank")
Edit . Added the code example
answered Feb 18, 2017 at 13:53
Sachin Gadagi
7495 silver badges14 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Shashank Shekhar
Thank You. It is helpful
lang-js
Person()=window.Person()newkeyword beforePerson