据我所知,构造函数无法生成函数:它们可以将属性分配给 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
, apply
或bind
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/