在下面的代码中,我无法将b实例化为新的a(),但能够将其作为新的f()进行实例化。我的结论是新的工作,对象必须是函数的直接/直接后代。那是准确的吗?我对javascript相对较新,并且正努力从根本上理解该语言。感谢,
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");
function A() {}
console.log("Prototype of A:" + A.prototype);
console.log("Constructor of A:" + A.constructor);
console.log("Prototype Link of A:" + A.__proto__);
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");
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__);
// b = new a();
// error: Uncaught TypeError: object is not a function (anonymous function)

答案 0 :(得分:0)
看看那个......
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 instanceof Function");
if (f instanceof Object) console.log("f instanceof Object");
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 instanceof Function");
if (A instanceof Object) console.log("A instanceof Object");
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 A) console.log("a instanceof A");
if (a instanceof Object) console.log("a instanceof Object");
答案 1 :(得分:0)
Function constructor创建一个新的Function对象。在JavaScript中 每个函数实际上都是一个Function对象。
var f = new Function();//f is a function and not an normal object
var b = new f();//work expected as f is a function
新a()不起作用的原因
function A() {}//A is function
var a = new A();//a is not a function rather an object
var b = new a();//throw error as 'new' expect function
<强> new operator: 强> 新运算符需要constructor function。
var a = new foo[([arguments])]//foo must be a function.
当执行代码new foo(...)时,会发生以下情况:
this
绑定到新创建的对象。 new foo等同于新的foo(),即如果没有指定参数列表,则不带参数调用foo。构造函数返回的对象成为整个新表达式的结果。如果构造函数没有显式返回对象,则使用在步骤1中创建的对象。 (通常构造函数不会返回值,但如果他们想要覆盖正常的对象创建过程,他们可以选择这样做。) e.g
function f() {
this.y = 50;//will be overridden due to below return statement
return function () {
this.x = 5;
}
}
var b = new f();//b is a function as f() is returning a function and hence it will override the normal function creation
alert(b.y);//undefined as y is no more property of instance b as function constructer has a return statement returning object(function object in this case)
var c = new b();
alert(c.x);//c.x = 5;