A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype below:

Function.prototype.prototype - JavaScript | MDN

在使用 new 运算符调用函数时,构造函数的 prototype 属性将成为新对象的原型。

function Ctor() {}
const inst = new Ctor();
console.log(Object.getPrototypeOf(inst) === Ctor.prototype); // true

关于构造函数的 prototype 属性与结果对象的原型之间的相互作用,你可以查看继承与原型链来了解更多。

一个具有 prototype 属性的函数也并不代表其有资格作为构造函数。例如,function* 拥有 prototype 属性,但它不能通过 new 运算符来调用。

async function* asyncGeneratorFunction() {}
function* generatorFunction() {}

反之,生成器函数通常在它们不被 new 运算符调用的时候被用到它们的 prototype 属性。 prototype 属性会作为返回的 Generator 对象的原型。

另外,一些函数也可能在通过 new 运算符调用的情况下无条件抛出,即便它们可能具有 prototype。例如,Symbol() 和 BigInt() 函数会在它们通过 new 运算符来调用时抛出,因为 Symbol.prototype and BigInt.prototype 只是用来为原始值提供方法的,这时不应该直接构建包装器对象。

下列的函数不具有 prototype 属性,因此不能成为构造函数,即便后续手动赋予了 prototype 属性:

const method = { foo() {} }.foo;
const arrowFunction = () => {};
async function asyncFunction() {}

下列则可以成为合法的构造函数,因为它们具有 prototype:

class Class {}
function fn() {}

绑定函数不具有 prototype 属性,但是可能是可构造的。当它被构造的时候,目标函数将会被构造,如果目标函数是可构造的,将会返回一个普通的实例。

const boundFunction = function () {}.bind(null);

默认情况下,函数的 prototype 是一个普通的对象。这个对象具有一个属性:constructor。它是对这个函数本身的一个引用。 constructor 属性是可编辑、可配置但不可枚举的。

如果函数的 prototype 被赋予了 Object 以外的值,则当它被 new 运算符调用时,返回对象的原型将会指向 Object.prototype。(换句话说,new 运算符会忽略它的 prototype 属性并构造一个普通对象。)

function Ctor() {}
Ctor.prototype = 3;
console.log(Object.getPrototypeOf(new Ctor()) === Object.prototype); // true

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4