函数混淆的代价者

costructor of function confusion

本文关键字:代价 函数      更新时间:2023-09-26

在这种情况下为

var A = function(){
    this.d = 123;
}
A.prototype.c = 999;
A.prototype.d = 333;
var B = (new A()).constructor;
console.log(""+B);
console.log(new A().d); // 123
console.log(new B().d); // 123
console.log(new A().c); // 999
console.log(Object.getPrototypeOf(new B()).c); // 999 why?

A和B共享同一构造函数但B不是A,为什么有和A相同的原型?

在这种情况下,

var A = function(){
    this.d = 123;
}
A.prototype.c = 999;
A.prototype.d = 333;
var B = A.constructor;
console.log(""+B);
console.log(new A().d); // 123
console.log(new B().d); // undefined
console.log(B.d); // still undefined
console.log(new A().c); // 999
console.log(Object.getPrototypeOf(new B()).c); // undefined

B是A的构造函数,而不是他的实例的构造函数

什么是B?如何在没有A实例的情况下访问A的构造函数?

调用new A()时,将创建一个新的A对象,其原型为A.prototype。当您请求(new A()).constructor时,您正在从该A实例的原型链访问constructor属性;这将是CCD_ 7。

A本身就是一个Function对象。也就是说:AFunction的一个实例。当您请求A.constructor时,您正在从该Function实例的原型链访问constructor属性;这将是CCD_ 15。

在第一种情况下,BA是对完全相同函数的引用。完全可以预期new A()new B()的结果将具有相同的性质和相同的原型链。

在第二个示例中,BFunction构造函数,即构造函数的函数。调用new B()会创建一个新的Function对象。因此,new B()的结果不具有与A实例相同的属性。

要区分Anew A():

c = new A(); // This is an instance of A. The constructor property is A.
console.log(c.constructor) // function() { this.d = 123; }
console.log(new c.constructor()) // Creates another instance of A.
console.log(Object.getPrototypeOf(new c.constructor())) // A {c: 999, d: 333}
var c = A; // This is a function. The constructor property is a base Function.
console.log(c.constructor) // function Function() { [native code] }
console.log(new c.constructor()) // Creates instance of base Function.
console.log(Object.getPrototypeOf(new c.constructor())) // function Empty() {}

如果自定义构造函数(A)上没有new运算符,则不会创建A的实例。

有关new操作员的详细信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

尽管它已经得到了回答,但我没有看到它明确表示B是A(哦,它最近错过的APSiller提到了它):

var A = function(){};
var B = (new A()).constructor;
console.log(B===A,B===A.prototype.constructor
  ,A.prototype.constructor ===A);//true true true
//Something.prototype.constructor is a circular reference as constructor
//references Something
console.log(A.prototype.constructor.prototype.constructor.prototype
  .constructor.prototype.constructor === A);//true

构造函数附带原型并设置为构造函数函数,但您可以覆盖它(通常在继承时完成,因此您通常会看到它在继承后得到修复)

Child.prototype=Parent.prototype;
//Child.prototype.constructor now incorrectly refers to Parent
console.log(Child.prototype.constructor===Parent);//true
//repair constructor
Child.prototype.constructor=Child;

关于继承、构造函数和原型的更多信息,请点击此处。

由于所有对象都有一个原型(除非使用Object.create(null)创建),所有对象都具有指向创建它们的函数的构造函数属性:

console.log([].constructor===Array);
var arr = new [].constructor(1,2,3);//same as new Array(1,2,3)
console.log(arr);//[1,2,3]
//the following temporarily casts the string to String
console.log("hello".constructor===String);//true
//same with numbers
console.log(1..constructor===Number);//true
console.log(function(){}.constructor === Function);//true