views:

172

answers:

3

Why this is not working?

// this one works as I expected, when objSayHello()
Object.prototype.objSayHello = function(){alert('Hello,from OBJECT prototype')};
// NOT working !
Object.prototype ={objSayHello: function(){alert('Hello,from OBJECT prototype')}};

objSayHello();
+5  A: 
  1. Because you've replaced the Object prototype, so you're adding a objSayHello method to any object descending from Object (all objects).

  2. Don't replace Object.prototype.

What you probably want is:

someObj.prototype.objSayHello = function(){alert('Hello,from OBJECT prototype')};

Then to call it with:

someObj.objSayHello();

What you seem to be meaning to do is:

Object.prototype.objSayHello = function(){alert('Hello,from OBJECT prototype')};

But that is probably a bad idea as it will conflict with iterators (for...in) if not handled correctly.

eyelidlessness
+1  A: 
Object.prototype.objSayHello = function(to){alert('Hello, ' + to)};

The above statement means that you attached the objSayHello function to all the instances that will be created as every instance is child of Object so the attached event bind to all. For instance,

var newObject = {};
var anotherNewObject = new Object();

function person(name) {
 this.name = name;
}
var newPerson = new Person("Ramiz");

newObject.objSayHello("newObject");
anotherNewObject.objSayHello("anotherNewObject");
newPerson.objSayHello(this.name);

While, the other statement is incorrect and will be ignored completely as you're about to discard the prototype of an object which is parent of all. If the prototype of Object can be override then all native instances functionality will be gone. To avoid such a mistake I think this is ignore to be override.

Ramiz Uddin
+1  A: 

Object.prototype is for some reason a const, which means read only.

Jonas Magazinius