javascript“多态可调用对象”

我看到 this article on polymorphic callable objects并试图让它工作,但似乎它们不是真正的多态,或者至少它们不尊重原型链.

这段代码打印未定义,而不是“你好”.

这种方法不适用于原型,还是我做错了什么?

var callableType = function (constructor) {
  return function () {
    var callableInstance = function () {
      return callableInstance.calloverload.apply(callableInstance,arguments);
    };
    constructor.apply(callableInstance,arguments);
    return callableInstance;
  };
};

var X = callableType(function() {
    this.calloverload = function(){console.log('called!')};
});

X.prototype.hello = "hello there";

var x_i = new X();
console.log(x_i.hello);

解决方法

你需要改变这个:
var X = callableType(function() {
    this.calloverload = function(){console.log('called!')};
});

对此:

var X = new (callableType(function() {
    this.calloverload = function(){console.log('called!')};
}));

注意callableType调用周围的新括号和括号.

括号允许调用callableType并返回函数,该函数用作new的构造函数.

编辑:

var X = callableType(function() {
    this.calloverload = function() {
        console.log('called!')
    };
});

var someType = X();      // the returned constructor is referenced
var anotherType = X();   // the returned constructor is referenced

someType.prototype.hello = "hello there";  // modify the prototype of
anotherType.prototype.hello = "howdy";     //    both constructors

var some_i = new someType();           // create a new "someType" object
console.log(some_i.hello,some_i);

var another_i = new anotherType();     // create a new "anotherType" object
console.log(another_i.hello,another_i);

someType();      // or just invoke the calloverload
anotherType();

我真的不知道你使用这种模式的方式/地点/原因,但我想有一些很好的理由.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...