javascript“多态可调用对象”

编程入门 行业动态 更新时间:2024-10-28 08:26:18
本文介绍了javascript“多态可调用对象”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我看到了这篇关于多态可调用对象的文章,并试图将其发布到工作,但似乎他们不是真正的多态,或者至少他们不尊重原型链。

I saw this article on polymorphic callable objects and was trying to get it to work, however it seems that they are not really polymorphic, or at least they do not respect the prototype chain.

此代码打印 undefined ,而不是你好。

此方法不适用于原型,或者是我做错了什么?

Does this method not work with prototypes, or am I doing something wrong?

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!')}; }));

注意 new 以及括号围绕 callableType 调用。

Notice the new as well as the parentheses around the callableType invocation.

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

The parentheses allows callableType to be invoked and return the function, which is used as the constructor for 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();

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

I really don't know how/where/why you'd use this pattern, but I suppose there's some good reason.

更多推荐

javascript“多态可调用对象”

本文发布于:2023-08-04 00:54:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1291474.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   多态   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!