javascript的prototype的问题。

2025-02-26 23:50:29
推荐回答(3个)
回答1:

这个还真不好说,跟javascript的继承关系有关。

当A继承与B时,代码如下

A.prototype = new B;
alert(A.prototype instanceof B);     //结果为true

js中所有类都继承与Object类,其实Object与function() {}是一样的,这里的function是小写,

function fun01() {};
alert(fun01 instanceof Object);    //结果为true

所以fun01.prototype结果是Object;

而fun01.constructor是一个方法类,它不是直接继承与Object,而是直接继承于Function并且通过是原型链共享获得继承的,这里是首字母大写的Function,以下代码可以证明:

var con = fun01.constructor;
alert(con.prototype === Function.prototype);     //结果为true

然后Function才继承与Object类

alert(Function.prototype instanceof Object);     //结果为true

所以才有fun01.constructor.prototype返回一个Function,而fun01.prototype返回一个Object。

回答2:

(1)function的prototype都是object
这里的函数具体来讲是指函数对象function,而不是Function,function是由Function构造出来的;
(2)fun.constructor.prototype=function prototype(){}
这个分两步:fun.constructor是Function,而Function的原型则是function prototype(){}函数---这个问题很少有人提及,主要在编程时很少用到。

回答3:

本来想看看你这个题的,结果发现还真不容易解释,我发现除了Function的prototype,其他的Array、Number啥的都是object,不知道如何解释

function f1(param){return param*2;}
console.log(typeof f1.prototype);//object
console.log(typeof f1.constructor.prototype);//function

var a=f1.constructor==Function;
console.log(a);//true
console.log(typeof Function.prototype);//function
console.log(typeof Array.prototype);//object
console.log(typeof Number.prototype);//object

 没辙,制定这门语言规范的人就是这么规定的吧。参考:http://ecma262-5.com/ELS5_HTML.htm#Section_15.3.4