当我有我想用作构造函数的函数时,请说:functionclog(x){vartext=x;returnconsole.log(text);}我已经做了一些实例varbla=newclog();现在我想添加新功能,所以我会使用clog.prototype.alert=alert(text);如果我只是这样做会有什么区别:clog.alert=alert(text);这不会被clog的对象继承吗?是他们的原型(prototype)吗? 最佳答案 由构造函数创建的实例(在您的情况下为clog)继承对clog.prototype的引用。目的
让我们看两个例子,我将在其中尝试解释我想理解的内容。varCar=function(){//InitclassfunctionCar(){};//Privatefunc/varsvarprivate={color:'red'};//Publicfunc/varsCar.prototype={newColor:function(color){private.color=color},getColor:function(){returnprivate.color}};returnCar.prototype;//returnwithprototype};varmyCar=newCar();和
人们常说每个Javascript对象都有一个prototype属性,但我发现只有当foo时foo.prototype才有值是一个函数。在Chrome和Firefox上,obj.__proto__有一个值——这是prototype属性吗?但是在IE9上,它不会工作(有什么方法可以吗?),我认为通过prototype属性,这意味着obj.prototype应该工作?我明白Object.getPrototypeOf(obj)似乎显示了这个prototype属性,但为什么需要一个特殊的方法来获取它?为什么不像person.name,就是获取person对象的name属性呢?更新:顺便说一下,o
我在document.ready()中定义了console.log的替代品:$(document).ready(function(){console.log("docready");if(typeofconsole==="undefined"){console={log:function(){}};}}我以为IE应该有这个功能,但是,当我包含上面的调用时console.log("docready");输出出现在Firefox控制台中,但不出现在IE中-实际上IE脚本执行在此时完全中断。在IE中写入控制台的正确方法是什么? 最佳答案
自从我了解原型(prototype)继承以来,我一直想知道为什么将父类的实例而不是原型(prototype)本身推送到子原型(prototype)中?varAnimal=function(type){this.type=type;}Animal.prototype.getType=function(){returnthis.type;}varCat=function(options){this.breed=options.breed;}//InheritanceCat.prototype=newAnimal('Cat');为什么不这样继承呢?Cat.prototype=Animal.p
我一直在玩JavaScript,特别是用类和诸如此类的东西模拟面向对象的编程。我知道这种实现继承的方式MyClass.prototype=newAnotherClass();但我并不满意,我不喜欢我需要如何调用AnotherClass的构造函数。所以我一直在玩,想出了一些似乎有效的东西,基本上想要第二个意见。functionclone(obj){functionCloneFactory(){}CloneFactory.prototype=obj;returnnewCloneFactory();}MyClass.prototype=clone(AnotherClass.prototype
functiona(){return"foo";}a.b=function(){return"bar";}functionc(){};c.prototype=a;vard=newc();d.b();//returns"bar"d();//throwsexception,disnotafunction有没有办法让d成为一个函数,同时仍然继承a的属性? 最佳答案 实际上,事实证明这是可能的,尽管是以非标准的方式。Mozilla、Webkit、Blink/V8、Rhino和ActionScript提供了一个非标准的__proto__属性,
我遇到过两种将数组原型(prototype)应用于native对象的方法:arr=Array.prototype.slice.call(obj);arr=[].slice.call(obj);以类似的方式,获取原生类数组对象的真实类型:type=Object.prototype.toString.call(obj);type={}.toString.call(obj);一个简单的测试:functionfn(){console.log(Array.prototype.slice.call(arguments),[].slice.call(arguments),Object.prototy
这个问题在这里已经有了答案:Useof'prototype'vs.'this'inJavaScript?(15个答案)关闭8年前。将方法“area”定义为“this”而不是“prototype”的属性有什么区别?//console.clear()functionRectangle(w,h){this.width=w;this.height=h;this.area=function(){returnthis.width*this.height;}}varr=newRectangle(2,3);vara=r.area();//console.log(a)functionSquare(s){
我写了从Person继承reader的简短代码:/*ClassPerson.*/functionPerson(name){this.name=name;}Person.prototype.getName=function(){returnthis.name;}varreader=newPerson('JohnSmith');alert(reader.getName());或者我可以删除Person.prototype.getName=function(){returnthis.name;行}并在Person对象中创建它。例如/*ClassPerson.*/functionPerson(