[英]Function constructor in Crockford's pseudoclassical inheritance section
What does he mean by this: 他的意思是:
"When a function object is created, the Function constructor that produces the function object runs some code like this:
“创建函数对象时,生成函数对象的Function构造函数会运行如下代码:
this.prototype = {constructor: this};
The new function object is given a prototype property whose value is an object containing a constructor property whose value is the new function object"
新函数对象被赋予一个prototype属性,其值是一个包含构造函数属性的对象,其值为新函数对象“
Explanation with an example would be great. 用例子解释会很棒。
For example, when you define this constructor: 例如,当您定义此构造函数时:
function MyConstructor() {
// ...
}
It automatically receives a prototype
property. 它会自动接收
prototype
属性。 Its value is an object with a constructor
property, which points back to the constructor: 它的值是一个带有
constructor
属性的对象,它指向构造函数:
MyConstructor.prototype; // some object
MyConstructor.prototype.constructor; // MyConstructor
This is specified in Creating Function Objects : 这在创建函数对象中指定:
- Create a new native ECMAScript object and let F be that object.
创建一个新的本机ECMAScript对象,让F成为该对象。
- Let proto be the result of creating a new object as would be constructed by the expression
new Object()
whereObject
is the standard built-in constructor with that name.让proto成为创建一个新对象的结果,该对象将由表达式
new Object()
构造,其中Object
是具有该名称的标准内置构造函数。- Call the [[DefineOwnProperty]] internal method of proto with arguments
"constructor"
, Property Descriptor {[[Value]]: F , { [[Writable]]: true , [[Enumerable]]: false , [[Configurable]]: true }, and false .使用参数
"constructor"
调用proto的[[DefineOwnProperty]]内部方法, 属性描述符 {[[Value]]: F ,{[[Writable]]: true ,[[Enumerable]]: false ,[[Configurable]] : true }, false 。- Call the [[DefineOwnProperty]] internal method of F with arguments
"prototype"
, Property Descriptor {[[Value]]: proto , { [[Writable]]: true , [[Enumerable]]: false , [[Configurable]]: false }, and false .使用参数
"prototype"
调用F的[[DefineOwnProperty]]内部方法, 属性描述符 {[[Value]]: proto ,{[[Writable]]: true ,[[Enumerable]]: false ,[[Configurable]] : false }, false 。
Then, instances of the constructor will inherit from its prototype
object: 然后,构造函数的实例将从其
prototype
对象继承:
var myInstance = new MyConstructor();
Object.getPrototypeOf(myInstance); // MyConstructor.prototype
In case you want to know the constructor used to create the instance, you can use the constructor
property, which hopefully will be inherited: 如果您想知道用于创建实例的
constructor
,可以使用constructor
属性,希望将继承该属性:
myInstance.constructor; // MyConstructor
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.