我是一位经验丰富的面向对象程序员,但这让我受益匪浅!为什么我能够做新的f()而不是新的a()。我会感激任何指示。
// first a few facts
if (Object instanceof Function) console.log("Object isa Function");
console.log("Function.prototype is " + Function.prototype);
/* output
Object isa Function
Function.prototype is function Empty() {}
*/
var f = new Function();
console.log("Prototype of f:" + f.prototype);
console.log("Constructor of f:" + f.constructor);
console.log("Prototype Link of f:" + f.__proto__);
if (f instanceof Function) console.log("f isa Function");
/* output
Prototype of f:[object Object]
Constructor of f:function Function() { [native code] }
Prototype Link of f:function Empty() {}
f isa Function
*/
function A() {}
console.log("Prototype of A:" + A.prototype);
console.log("Constructor of A:" + A.constructor);
console.log("Prototype Link of A:" + A.__proto__);
if (A instanceof Function) console.log("A isa Function");
/*
Prototype of A:[object Object]
Constructor of A:function Function() { [native code] }
Prototype Link of A:function Empty() {}
A isa Function
*/
// contruct a
var a = new A();
console.log("Prototype of a:" + a.prototype);
console.log("Constructor of a:" + a.constructor);
console.log("Prototype Link of a:" + a.__proto__);
if (a instanceof Function) console.log("a isa Function");
if (a instanceof A) console.log("a isa A");
/* output
Prototype of a:undefined
Constructor of a:function A(){}
Prototype Link of a:[object Object]
a isa A
*/
console.log("~~~~~b constructed as new f()");
var b = new f();
console.log("Prototype of b:" + b.prototype);
console.log("Constructor of b:" + b.constructor);
console.log("Prototype Link of b:" + b.__proto__);
/* output
~~~~~b constructed as new f()
Prototype of b:undefined
Constructor of b:function anonymous() {}
Prototype Link of b:[object Object]
*/
console.log("~~~~~b constructed as new a()");
a.prototype = Object.prototype;
a.constructor = Function;
a.__proto__ = Function.prototype;
if (a instanceof Function) console.log("a isa Function");
console.log("Prototype of a:" + a.prototype);
console.log("Constructor of a:" + a.constructor);
console.log("Prototype Link of a:" + a.__proto__);
/* output
~~~~~b constructed as new a()
a isa Function
Prototype of a:[object Object]
Constructor of a:function Function() { [native code] }
Prototype Link of a:function Empty() {}
*/
b = new a();
/* ERROR Uncaught TypeError: object is not a function*/
我也尽力提供输出。注意f和a在原型,构造函数和原型链接方面是相同的。当我尝试在最后一行中新建a()时,为什么会出现ERROR?
答案 0 :(得分:1)
正如错误所指出的那样,a
应该是函数,也就是说,它必须是可调用的。 new
关键字需要一个知道如何构造实例的函数对象 - 但a
不能。让它继承自Function.prototype
(使用__proto__
)对任何事都没有帮助,可调性是对象的固有属性。
您可以致电new f()
,因为f
是这样的构造函数,由Function
constructor创建。