Javascript: Is It Possible To Inject New Functions Into A Base 'class/object' That Will Be Available In All Sub-'classes/objects'?
Solution 1:
The way prototypical OO works is that when you :
- Look up a property on an object, say
imageContainer
- It will look for properties on that object,
- If it can't find any it will look on the prototype (
ImageContainer.prototype
) - If it can't find any it will look on the next prototype ('Container.prototype')
- And the next prototype ('Object.prototype') until the prototype chain is empty in which case it returns
undefined
.
This means if you add a property GUID
Container.prototype.GUID = 42;
All objects with Container.prototype
in the prototype chain will share that property.
If you do not want that property to be shared then it's very difficult to add a unique GUID to all objects with Container.prototype
in their prototype chain.
You can however use .isPrototypeOf
to check whether an object has a prototype in their chain.
Example:
var objs = [..]; // all objects
objs.forEach(function(v) {
if (Container.prototype.isPrototypeOf(v)) {
v.GUID = window.GUID++;
}
});
This however relies on
- ES5. Use the ES5-shim
- You being able to create the array
objs
with all the objects you might want to extend.
Solution 2:
As already described, if GUID is a function you can simply add it to the container prototype. If not, adding this function
container.prototype.GUID = function (v) {
if (arguments.length) // setting the value
return this.GUID = v;
return this.hasOwnProperty ('GUID') ? this.GUID : undefined;
}
Will allow you to access a GUID property by using obj.GUID ()
or set it using obj.GUID (val)
Solution 3:
If i understood you well, here is an example:
And here with automatic unique GUID's:
Post a Comment for "Javascript: Is It Possible To Inject New Functions Into A Base 'class/object' That Will Be Available In All Sub-'classes/objects'?"