-->

[removed] Is it possible to inject new functions i

2019-08-24 02:05发布

问题:

I am trying to add a new property to a class in an existing JavaScript framework (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?

回答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.


回答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)



回答3:

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/