[英]Why does `instance.constructor.staticProperty` in TypeScript not work?
[英]What is instance.constructor.constructor and how does it work?
function Person(name) {
this.name = name;
}
let person1 = new Person("Eve");
person1.constructor; // Output: ƒ Person(name) {}
person1.constructor.constructor; // Output: ƒ Function() { [native code] }
person1.constructor.constructor("console.log(1)"); // Output: ƒ anonymous() {console.log(1)}
person1.constructor.constructor("console.log(1)")(); // Output: 1
有人可以帮我理解person1.constructor.constructor
、 person1.constructor.constructor("console.log(1)")
和person1.constructor.constructor("console.log(1)")()
吗? 我不明白输出。
实例的.constructor
属性指向与内部原型关联的 function。 如您所见, person1.constructor
为您提供Person
,因为person1
是使用new Person
创建的( person1
的内部原型是Person.prototype
)
什么是Person
? 这是一个 function。 The .constructor
of a function will be the function associated with the internal prototype of that function - that is, the constructor associated with Function.prototype
, which is Function
, the function constructor:
function Person(name) { this.name = name; } let person1 = new Person("Eve"); console.log(person1.constructor.constructor === Function);
您可以将字符串传递给new Function
以从中创建函数。
person1.constructor.constructor("console.log(1)");
就像
Function("console.log(1)");
它返回一个 function ,调用时记录 1。
const fn = Function("console.log(1)"); console.log(fn); fn();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.