javascript - ECMAscript 是否提供了构造函数的方法?

标签 javascript types constructor

据我所知,构造函数无法生成函数:它们可以将属性分配给 this,并为通用和其他属性提供立即的 prototype 引用。因此不是特定于实例的。但不可能直接向 this 分配任何内容。即使是这样,逻辑结果也是用赋值替换实例及其原型(prototype)链。

根据我对 ES6 类的了解,它们相当于将构造函数声明和原型(prototype)实例化分组到单个语句中的语法糖。

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

最佳答案

编辑

I'm interested in functions which are instances of other functions

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"

使用不同的 this 调用函数通过使用call , applybind

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

关于javascript - ECMAscript 是否提供了构造函数的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27591648/

相关文章:

typescript - 为什么这段代码没有给我一个带有 --noImplicitAny 的错误?

c++ - 成员变量不保存从函数成员添加到它的值

javascript - 谷歌驱动器 API : Correct way to upload binary files via the Multipart API

javascript - Angular 4 : can't update the query string of URL

typescript - 如何在 TypeScript 中为 css 颜色定义类型?

java - 键/值对 : call a method key with params , 返回用 params 构造的值

java - 这是一个什么样的构造函数,以 <T extends Drawable & DrawerToggle> 开头?

javascript - 使用智能手机相机识别字母

javascript - 使用设置为 ng-click 的变量来更改模板

python - Python中调用C函数的问题