问题描述
var constructor = function(){ var name='eric'; function getName(){ return name; } function setName(inName){ name= inName; } return function(){ return{ getName:getName, setName:setname } }}()var obj = constructor();obj.getName();//ericobj.setName('naruto');//narutovar obj2 = constructor();obj2.getName();//naruto 但我希望obj1,obj2互相独立,只有getName方法共享,如何才能办到?
解决方案
var constructor = function(){ var name='eric'; constructor.property.getName = function(){ return name; } constructor.property.setName= function(inName){ name= inName; } return this;}var obj = constructor();obj.getName();//ericobj.setName('naruto');//narutovar obj2 = constructor();obj2.getName();//eric手写,未测试如果有疑问,看完下面的链接你一定会了。http://www.w3school.com.cn/js/pro_js_object_defining.asp
解决方案二:
(function(){var constr=window.constr=function(){ return new constr.fn.init(); }; constr.fn=constr.prototype={name:'eric',init:function(){return this;},getName:function(){return this.name;},setName:function(inName){this.name=inName;} }; constr.fn.init.prototype = constr.fn;})();var obj =window.constr();obj.getName();//ericobj.setName('naruto');//narutoalert(obj.getName());var obj2 =window.constr();alert(obj2.getName());//naruto Jquery的方式。测试通过。适合你