假设我想创建以下API:varapi=function(){}api.prototype={constructor:api,method:function(){returnthis;}};现在,这将像这样工作:varmyApi=newapi();myApi.method();但是假设我想让new关键字成为可选的,这样它就可以工作了:api().method();我会疯狂地做:varapi=function(){if(!(thisinstanceofapi)){returnnewapi();}};但我想知道,这是否很容易以某种方式被感染,或者使用这种方法还有其他危险吗?我知道f.exjQ
functioncatRecord(name,birthdate,mother){return{name:name,birth:birthdate,mother:mother};}我对构造函数的理解是一个用于构建对象的函数。这个catRecord函数算作构造函数吗? 最佳答案 不,您提供的函数返回一个没有类型信息的新关联数组。您所追求的构造函数是这样的:functionfixedCatRecord(name,birthdate,mother){this.name=name;this.birthdate=birthdate;this.
作为RPG游戏后端的一部分,我希望能够对Angular色应用临时效果。这些影响的性质可能有很大差异,但我想保持定义它们的方法非常简单。我将自定义事件处理用作混合:varEvtObject={};$rpg.Event.enable(EvtObject);//Addthe3methodsandsetEvtObject._events={}我想将Auras(临时效果)定义为带有事件处理代码的构造函数:varMyAura=function(any,args){this.group="classification";this.on("tick",function(){});this.on("re
入门读物:Prototypesas"classes"OOJS按照上述模式,我创建如下库/APIvarProto={constructor:function(){this.works=true;},method:function(){returnthis.works;}};现在库用户要与我的原型(prototype)(不提供工厂函数)交互,他们必须实例化和初始化对象//instantiatevarp=Object.create(Proto);//initializep.constructor();这是一种强制用户实例化和初始化我的对象的不友好且冗长的方式。我个人使用pd在我所有的应用程序
我在使用Typescript时遇到问题,我扩展了一个类并从父类(superclass)覆盖了一个属性,但是当我实例化子类时,父类(superclass)属性仍然在构造函数中读取。请看下面的例子:classPerson{publictype:string='GenericPerson';publicconstructor(){console.log(this.type);}}classClownextendsPerson{publictype:string='ScaryClown';}varperson=newPerson(),//'GenericPerson'clown=newClow
假设我有一个函数Foo,我希望从它构造的对象有一个bar属性:functionFoo(){}Foo.prototype.bar='baz'console.log('newFoo().bar:'+newFoo().bar)newFoo().bar:baz现在假设我bindFoo以某种方式。绑定(bind)函数仍然可以在构造函数调用中使用,绑定(bind)的this将被忽略:constBound=Foo.bind(42)console.log('newBound().bar:'+newBound().bar)newBound().bar:bazProxies应该是一般和透明的。然而……co
这个问题在这里已经有了答案:What'sthedifferencebetweenusinginstanceofandcheckingtheconstructor?(2个答案)Differencebetweeninstanceofandconstructorproperty(2个答案)关闭4年前。假设我有一个Dog构造函数functionDog(name){this.name=name;}我有一个构造函数的实例constmyDog=newDog('Charlie');据我最近了解到,有两种方法可以检查myDog是否是Dog的实例:1.console.log(myDoginstanceof
如果我有这样的功能:functiona(){console.log('a');}然后像这样分配一个静态属性:a.static='foo';但是假设我想用这样的另一个函数覆盖该函数:varold=a;a=function(){console.log('new');old.call(this);};a.static//undefined自从我为a分配了一个新函数后,它的静态属性就丢失了。有没有一种巧妙的方法来保留静态属性而无需循环和手动复制它们?更新:这是一个真实的场景:在BootstrapjQuery插件中,作者将默认值分配给属性函数,如下所示:$.fn.modal=function()
前几段描述了我要实现的目标,实际问题在最后。谢谢以前,我只是简单地使用new关键字来创建对象,使用原型(prototype)来分配方法和处理继承。然而,最近(部分受到CoffeeScript生成的JS的启发)我决定使用一个对象创建函数,它看起来像这样:varTest=function(a){functionTest(a){this.a=a;}varnumCalls=0;Test.prototype.output=function(){alert('Iwasinitializedwith'+this.a);numCalls++;};Test.prototype.called=functi
考虑MDN'sObject.createpolyfill:if(typeofObject.create!='function'){(function(){varF=function(){};Object.create=function(o){if(arguments.length>1){throwError('Secondargumentnotsupported');}if(o===null){throwError('Cannotsetanull[[Prototype]]');}if(typeofo!='object'){throwTypeError('Argumentmustbean