How to create a Wrapper

江枫思渺然 提交于 2019-12-06 04:57:46

问题


As I Googled particular things, I've numerously run into the concept of "create a wrapper and extend that." In my case, I want to extend DOM. I know how advised against that is, but what I'm trying to do is slightly different and to do it I need to at-least explore these methodologies. So my question to you, after not getting a straight answer nomatter what blog/wiki/tut I looked at, is: What is a wrapper object/function and how do you make and use one?

Sorry if it turns out I made no sense; I'm getting this idea from when I read that prototype library and JQuery did things of these sorts once upon a time. If you could use DOM as an example, it would be appreciated.


回答1:


Silly example, assuming <div id='my-div'></div>

MyDiv = {
  _e:document.getElementById('my-div'),
  setText:function(s) {
    this._e.innerText = s;
  },
  getText:function() {
    return this._e.innerText;
  },
  red:function() {
    this._e.style.backgroundColor = 'red';
  }
}

Wrapping the DOM element my_div inside MyDiv allows you to filter (or augment) the wrapped object's interface.

MyDiv.setText('Hello');
MyDiv.red();
alert(MyDiv.getText());


来源:https://stackoverflow.com/questions/9024528/how-to-create-a-wrapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!