user3645936 February 2016

Constructor functions in js

Trying to understand the outputs below - why are the checks false when directly used on objects - but true when checked on instances ?? can some one explain - am I missing something here?

    function Book2(){
    this.title =  "High Performance JavaScript";
    this.publisher = "Yahoo! Press";
};

Book2.prototype.author = "hgghghg";

var b = new Book2();

alert(Book2.hasOwnProperty("title"));  //false
alert(Book2.hasOwnProperty("toString"));  //false
alert("title" in Book2); //false
alert("toString" in Book2); //true


alert(b.hasOwnProperty("title"));  //true
alert(b.hasOwnProperty("toString"));  //false
alert("title" in b); //true 
alert("toString" in b); //true

Answers


Juan Mendes February 2016

hasOwnProperty does not look at the prototype chain, the in operator does

Also, Book is a function, it does not have its own properties, it inherits methods like apply and call. Creating an instance of Book with new will create an object whose prototype chain starts with Book.prototype so it will see properties like title.


deceze February 2016

Book2 does not have a title attribute, it only sets a title attribute on a new object. Book2 does inherit the toString method from its prototype.

hasOwnProperty, as the name suggests, tells you whether this particular object itself has the given property. It does not look at the prototype.
in tells you whether the object has the property anywhere, including its prototype chain.

Post Status

Asked in February 2016
Viewed 2,114 times
Voted 12
Answered 2 times

Search




Leave an answer