Skip to content Skip to sidebar Skip to footer

Copying Attributes In Javascript

Javascript - The Definitive Guide (6ed) shows the following code: Originally we have this function /* * Copy the enumerable properties of p to o, and return o. * If o and p have a

Solution 1:

The purpose of defining this in the prototype is so that every Object can call it as a member function, like this:

yourobject.extend(anotherObject);

Most coders find that more elegant than having to pass both objects as parameters, like this:

extend(yourObject, anotherObject);

Modifying prototypes is a great way to add useful "methods" to objects.

side note: I would not recommend using the author's extend code. It doesn't properly check hasOwnProperty.

Solution 2:

You seem to misunderstand the use of prototype. Prototyping is JavaScript's way of dealing with inheritance. The extend function is terminology loaned from languages like C++ and Java and is not native to JavaScript.

Here's a guide on prototype: http://mckoss.com/jscript/object.htm

I have several years experience writing JavaScript and I'd recommend not using prototyping at all. JavaScript has other ways of dealing with data modeling that I find more elegant. It's still useful to understand how prototyping works though because it deepens your understanding of Objects.

Post a Comment for "Copying Attributes In Javascript"