hereandnow78
hereandnow78

Reputation: 14434

Ownership of Javascript Object-Properties created via new

for example, if i use prototype.js inside my app, the library extends the Objects prototype with some additional stuff, eg:

// the code is not exactly like this but that doesnt matter
Object.prototype.inspect = function...

when i create some object, the object has NEVER the ownproperty "inspect", which of course is correct:

// false
{}.hasOwnProperty('inspect');

if i create an Object-literal like this, properties created via this object-literal are ownproperties, which of course is correct too:

var myObj = {
   myProp: 'myVal'
};

// this would return true here
myObj.hasOwnProperty('myProp');

BUT, if i create an object via the new operator, even the properties inside my Function are not recognized as ownproperty.

function MyTest () {}

MyTest.prototype.myProp = function () {};

var myObj = new MyTest();

// this would return false here

myObj.hasOwnProperty('myProp');

can somebody explain why it is like that? i want to iterate over an object, create a new object which only contains properties that are NOT part of the Objects.prototype (and therefore not created through prototype.js).

EDIT: im not the owner of the code that creates myObj, and i dont know which Function-Constructor creates myObj

EDIT2: thanks to niko, thats how i do it now:

var key, newObj = {};
for (key in oldObj) {
  if (typeof newObj[key] == 'undefined') {
    newObj[key] = oldObj[key];
  }
}
for (key in newObj) {
  if (newObj.hasOwnProperty(key)) {
    // do some stuff here with properties that did not came from the objects.prototype
  }
}

Upvotes: 2

Views: 289

Answers (2)

Niko
Niko

Reputation: 26730

The sole purpose of hasOwnProperty is to tell properties attachted to the actual object (aka the instance) apart from those attached to the prototype. If you construct an instance via the new operator, the new instance is linked to the prototype of the function it was constructed from - the properties of the prototype are not copied to the new instance!

Consider something like this to copy everything that is not in Object.prototype:

var newObj = {};
for (var key in oldObj) {
    if (typeof newObj[key] == 'undefined') {
        newObj[key] = oldObj[key];
    }
}

However, the properties of Object.prototype will still be accessible via newObj because it is an instance of, well, Object of course.

Upvotes: 3

Barney
Barney

Reputation: 16456

Because it's assigned to the prototype, which in effect is a bit like creating a nebulous class or ancestor for the object, and giving the property to that. The property was never directly assigned to myObj.

Worth noting that you could apply the prototype directly to myObj rather than its constructor, or apply myProp straight to myTest without invoking prototype, and myProp would still not be myObj's own property.

Upvotes: 1

Related Questions