xx3004
xx3004

Reputation: 788

How can I added functions to Object constructor using Object.prototype?

I've been coming along with those scripts these days and after bunches of research I still could not find the answer.

So here is the problem, I want to (for example) add a function into an Object (.length() for instance, since the native doesn't have this yet), I've tried:

Object.prototype.length = function() { /* Some fancy work */ }; //It works!

Object.prototype["width"] = function() { /* Some fancy work */ }; //It works!

/* But the following DOESN'T work */
Object.prototype = {
    length: function() { /* Some fancy work */ },
    width: function() { /* Some other fancy work */ }
};

The last one doesn't work, and that is the shortest way to add function using an Object {} like that, I have no clue why. I've come across those code (for example from jQuery 1.7.1), I've tried to figure out how it works but I doesn't work to me. I think it must work somehow since jQuery uses it, could you please show me how?

I've seen a lot of people using those code:

a = {
    b: "Something",
    c: function() {}
}

And others use:

a.prototype = {
    b: "Something",
    c: function() {}
}

So what is the difference? This is somehow related to the first question, so I really like to understand it completely.

Upvotes: 1

Views: 101

Answers (1)

bjornd
bjornd

Reputation: 22951

1) You can't use

Object.prototype = {
    length: function() { /* Some fancy work */ },
    width: function() { /* Some other fancy work */ }
};

because you're trying to replace the whole built-in functionality of the Object with only two methods. This will break the whole system.

2) Object.method() is an analogue for the static methods in other languages. It's owned by the pseudo-class, not by its every instance. At the same time Object.prototype.method is an analogue for regular method or field. It can be access only using instance.

3) Automatic function which will fire on object creation is Object. You can't modify since this is a built-in object.

Upvotes: 1

Related Questions