是否可以将对象原型上的方法组织到命名空间中? [英] Is it possible to organise methods on an object's prototype into namespaces?

查看:53
本文介绍了是否可以将对象原型上的方法组织到命名空间中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在JavaScript中实现特定的语法模式。本质上,要求是使用新方法扩展本机JavaScript对象的原型,并将这些方法组织到命名空间中。我正在寻找的结果可以概括为:

I'm trying to achieve a specific syntax pattern in JavaScript. Essentially, the requirement is to extend the prototypes of native JavaScript objects with new methods, and to organise those methods into namespaces. The result I'm looking for can be summed up as:

String.prototype.foo = {
    bar: function() { return this.toUpperCase(); } //Fails because "this" is foo, not it's parent string
};
'test'.foo.bar(); //should return 'TEST'

我知道还有其他方法可以获得类似的结果,但我真的我希望上面的语法是可能的 - 虽然我大约80%确定它不是。

I am aware there are other ways to achieve similar results but I really would prefer the syntax above is possible - although I'm about 80% sure that it's not.

我已经尝试了十几种不同的方法来构建它但我可以'找到任何方式到达字符串作为这内部栏()。我认为问题是因为 foo 是一个对象并且没有可执行代码,所以编译器无法将所有者this传递给它并从那里传递给子方法,但是我想知道是否存在一些我不知道的用于行走父链的模糊技术?接下来最好的事情可能是'test'.foo()。bar(),我没试过,但听起来更有可能工作。

I've tried a dozen different ways of constructing this but I can't find any way of reaching the string as "this" inside bar(). I believe the problem is that because foo is an object and has no executable code, there is no way for the compiler to pass the owner "this" to it and from there down to the child method, but I wondered if some obscure technique for walking the parent chain exists that I don't know about? The next best thing might be 'test'.foo().bar(), which I haven't tried, but sounds more likely to work.

推荐答案

当然,你走了:

Object.defineProperty(String.prototype,"foo", {
   get: function(){ 
        return { 
            bar: function(){ return this.toUpperCase() }.bind(this)
        }
   },
   enumerable: false, // don't show in for.. in loop
   configuratble: true,
});

"hello".foo.bar(); // "HELLO"

需要注意的几点:

  • defineProperty for defining a getter
  • Function::bind for fixing the this value.

这篇关于是否可以将对象原型上的方法组织到命名空间中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆