相关知识点:
构造函数、原型对象、实例对象
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { margin: 0; padding: 0; } .wrap { margin: 50px; 200px; height: 200px; border: 1px solid red; } .active { border-color: yellow; } </style> </head> <body> <div class="wrap" data-html="hello"></div> <script> function $(s) { return document.querySelector(s); } function attr(obj, data) { return obj.getAttribute(data); } function ChangeEle(obj) { this.ele = obj; this.ele.dataHtml = attr(this.ele, 'data-html'); } ChangeEle.prototype.myHtml = function () { var ele=this.ele; ele.innerHTML = ele.dataHtml; } ChangeEle.prototype.replaceStr = function (str) { var ele=this.ele; ele.innerHTML = ele.innerHTML === ele.dataHtml ? str : ele.dataHtml; } ChangeEle.prototype.addEvent = function (type, fn) { this.ele.addEventListener(type, fn); } var myWrap = new ChangeEle($('.wrap')); myWrap.myHtml(); myWrap.addEvent('click', function () { myWrap.replaceStr('world'); }); </script> </body> </html>