MDN表示Function object具有实例和原型属性(例如name
是Function
的实例属性)。所以我可以这样做:
function testA()
{
console.log("testA");
}
console.log(testA.name);
console.log(Function.name);
但是如何? Function
是object constructor function。将属性传递到其实例的唯一方法是通过.this
关键字将其保存到其prototype
,如下所示:
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
那些实例方法是什么,它们如何可用于Function
实例,例如testA
?
方法是属性,其中值是函数。由于name
是字符串,因此不是方法。
功能为have explicit rules for setting a name:
FunctionDeclaration:函数BindingIdentifier(FormalParameters) {FunctionBody}
- 如果FunctionDeclaration的功能代码是严格模式代码,请使strict为true。否则,使strict为假。
- 让名称为BindingIdentifier的StringValue。
- 让FunctionCreate(Normal,FormalParameters,FunctionBody,scope,strict)。
- 执行MakeConstructor(F)。
- 执行SetFunctionName(F,名称)。
- 将F。[[SourceText]]设置为与FunctionDeclaration匹配的源文本。返回F。
将属性传递给其实例的唯一方法是通过.this关键字将其保存到其原型中
没有this
指的是构造函数创建的对象,而不是其原型。
将属性传递给其实例的唯一方法是通过
.this
关键字将其保存到其原型,如下所示:
否,向this
添加属性不会将它们添加到函数的原型中。它将它们添加到调用中this
所指的位置;在您的示例中,假设您通过Person
(或类似名称)调用new
,那么它将是由Person
初始化的对象。它不会是Person
的原型(Function.prototype
),也不会是Person
的prototype
对象。
Function如何具有实例[属性和方法]?
函数是JavaScript中的对象。实际的真实物体。对象可以具有属性,其中一些属性可以引用函数,这实际上使它们成为实例方法。
那么Function
或testA
为什么具有name
属性?因为规范是这样说的。创建函数时:
function testA() {
// ...
}
...规范说它具有name
属性和其他一些属性(length
,在许多情况下为prototype
等)。它们是对象的“自有”属性。 (对象还继承了某些属性,例如apply
和call
。所有这些都是引用函数的属性;例如,它们是原型方法。)
与说明RegExp对象具有lastIndex
或flags
属性,或Map
对象具有size
属性的规范没有什么不同:
const rex = /./g;
console.log(rex.lastIndex); // 0
console.log(rex.flags); // "g" (on an up-to-date JavaScript engine)
console.log(new Map().size); // 0
您还可以向函数添加属性,因为...它们是对象:
function example(a, b) {
console.log("a = " + a + ", b = " + b);
}
example.sayLength = function() {
console.log("The length of this function is " + this.length);
};
example.sayLength(); // "The length of this function is 2"
函数是对象,就像其他任何对象一样。对象可以具有属性。因此,函数可以具有属性。真的就是这么简单。