user2022068
user2022068

Reputation:

Js: create html element that inherits from some js class

I have js class (if js supports classes is offtopic for this question):

var MyClass=function(){
....
}

MyClass.prototype.someMethod=function(){
...
}

I want to create html element (for example div) that will inherit MyClass. For example for custom elements I could use the following:

  var SimpleTableClass = document.registerElement('simple-table',{prototype: new MyClass()});
  simpleTable=new SimpleTableClass();

The only idea I have is:

var newDiv = document.createElement("div");
newDiv.prototype=new MyClass();

But I don't know if it's safe method, because I will override all html element prototype.

If it's possible I'd like to get not only html element but and its constructor (class) as in example with SimpleTableClass.

Upvotes: 1

Views: 301

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074138

The only idea I have is:

var newDiv = document.createElement("div");
newDiv.prototype=new MyClass();

But I don't know if it's safe method, because I will override all html element prototype.

More importantly than whether it's safe, it's pointless. :-) It creates a prototype property on the div, which does nothing to give it any methods from the MyClass instance.

You could extend the element with all of the methods from MyClass.prototype (or from an instance of MyClass) by copying their references to the element. Many libraries provide a function typically called extend that does exactly that. (Here's jQuery's, here's Underscore's.) This is usually called a "mixin." There's no inheritance there, you're just grabbing the references. It's safe enough other than the usual warnings about naming conflicts on expando properties. To minimize the odds of naming conflicts, you could prefix your methods with some, well, prefix.

For instance:

var MyStuff = {
  myDoThis: function() {
    // ...
  },
  myTurnGreen: function() {
    this.style.color = "green";
  }
  // ...and so on...
};

var div = document.createElement('div');
div.innerHTML = "This is the text of my div";
document.body.appendChild(div);
Object.keys(MyStuff).forEach(function(key) {
  div[key] = MyStuff[key];
});
setTimeout(function() {
  div.myTurnGreen();
}, 500);

Upvotes: 2

Related Questions