Twisted
Twisted

Reputation: 17

Why does hasOwnProperty('toString') not work on an object?

I recently watched a guide and wanted better understanding about the concept of hasOwnProperty.

According to Mozilla:

"The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as own (not inherited) property."

I created an object

var test = {yes:function(){}}

and then did

test.hasOwnProperty('toString')

and it returned false. Its because toString is a method that i did NOT create right inside test right?

But then if I log hasOwnProperty to an array and pass length, so

var arr1 = new Array
arr.hasOwnProperty('length') //appears to return true

It returns true, but I never declared length.

I thought hasOwnProperty only works on properties NOT inherited -

so why does using hasownprop('length') on an array return true when the array object inherits the length property,

but

var test = {yes:function(){}}
test.hasOwnProperty('toString') //false

why^ does this return false? toString is method on the object's prototype and I see it when I log it into the Google Chrome Console

Upvotes: 0

Views: 613

Answers (1)

Bergi
Bergi

Reputation: 664970

Its because toString is a method that I did NOT create right inside test right?

Yeah, objects created from object literals only do have the own properties that are declared in the literal.

But that you did not explicitly declare a property does not mean that it is inherited, or that it doesn't exist. Arrays do have an own .length property that is basically created by the array constructor - in the new Array call.

Imagine the following:

function Test() {
    this.prop = "some value";
}
var x = new Test;
console.log(x.hasOwnProperty("prop")) // what do you expect?

Upvotes: 1

Related Questions