一,JS扩展方法
JS中,想给原有对象增加属性或方法,但又不想修改原有的对象代码,那就借助prototype来扩展原有对象吧
function testObj(name,age){ this.name=name; this.age=age; return this; } // 给对象添加sex属性 testObj.prototype.sex=null; var user = new testObj('hello','20'); user.sex='m'; console.log(JSON.stringify(user,null,2));
二,JQ扩展方法
JQ中,可以为jQuery(或者写成$)本身扩展方法;也可以为所选对象扩展方法
// 为jQuery本身扩展方法 $.extend({ testExtendSay:function(sth){ console.log("testSay:"+sth); } }); $.testExtendSay('hello'); // 为所选对象扩展方法 $.fn.extend({ testFnExtendSay:function(sth){ console.log("testSay:"+sth); } }); $('#container').testFnExtendSay('world');
Leave a Reply