ECMAscript 是否提供任何构造函数的方法?

Does ECMAscript offer any ways of constructing functions?

本文关键字:方法 构造函数 任何 是否 ECMAscript      更新时间:2023-09-26

我所知,构造函数无法生成函数:它们可以将属性分配给this,并为其他泛型属性提供即时prototype参考,因此不是特定于实例的属性。但是不可能直接将任何东西分配给this。即使是这样,合乎逻辑的结果也是用赋值替换实例及其原型链。

从我读到的 ES6 类来看,它们相当于在单个语句中对构造函数声明和原型实例化进行分组的语法糖。

我的实际兴趣在于instanceof运算符的值,即断言 X 符合 Y 的高阶描述,而无需任何鸭子类型。特别是,鸭子打字是不可取的,因为它依赖于Y本身外部的Y的某种定义。

Edit

我对作为其他函数实例的函数感兴趣

ECMAScript 6 中,你应该能够在函数上调用Object.setPrototypeOf,但不建议这样做,尽管在 JavaScript 中函数也是一个对象,但最终可能会遇到意外的行为

function foo() {}
function bar() {}
Object.setPrototypeOf(bar, foo.prototype);
bar instanceof foo; // true
bar.constructor === foo; // true

我不完全确定你在问什么,但希望这些代码示例能帮助你

从使用 new 调用的函数返回对象

function Foo() {
    // a constructor
}
function Bar() {
    // another constructor
    return new Foo();
}
var b = new Bar();
b instanceof Bar; // false
b instanceof Foo; // true

使用new Function

function Fizz() {
    return new Function('return "Buzz";');
}
var b = Fizz();
b(); // "Buzz"

使用 callapplybind 调用具有不同this函数

function hello() {
    return this;
}
hello(); // window, null or error depending on environment
hello.call({'foo': 'bar'});  // {'foo': 'bar'}
hello.apply({'foo': 'bar'}); // {'foo': 'bar'}
var b = hello.bind({'fizz': 'buzz'});
b(); // {'fizz': 'buzz'}

扩展构造函数

function Foo() {
    this.foo = 'foo';
}
Foo.prototype = {'fizz': 'buzz'};
function Bar() {
    Foo.call(this);
    this.bar = 'bar';
}
// and link in inheritance
Bar.prototype = Object.create(Foo.prototype);
var b = new Bar();
b.bar; // "bar"
b.foo; // "foo"
b.fizz; // "buzz"
b instanceof Bar; // true
b instanceof Foo; // true
// but
Bar instanceof Foo; // false

构造函数可以构造函数。如果构造函数返回一个对象,则构造函数返回的对象将成为整个new表达式的结果。

请参阅 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

由于函数是对象,因此您也可以从构造函数返回它们,如下所示:

function Shout(text) {
  return function () {
    alert(text);
  };
 }
shout1 = new Shout('hola');
shout2 = new Shout('eeee');
shout1();  // hola
shout2();  // eeee