开发者

Javascript: Is it possible to inject new functions into a base 'class/object' that will be available in all sub-'classes/objects'?

开发者 https://www.devze.com 2023-03-22 03:59 出处:网络
I am trying to add a new property to a class in an existing JavaScript framework 开发者_C百科(Wireit).

I am trying to add a new property to a class in an existing JavaScript framework 开发者_C百科(Wireit).

The base class is called Container and I want all Containers to have a GUID property. Container is currently sub-classed to ImageContainer, FormContainer etc.

If I extend Container to have a GUID, would the GUID be available in ImageContainer, FormContainer etc.?

How would I do this? Examples?


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.


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)


If i understood you well, here is an example:

http://jsfiddle.net/mMfdj/1/

And here with automatic unique GUID's:

http://jsfiddle.net/mMfdj/5/

0

精彩评论

暂无评论...
验证码 换一张
取 消