JavaScript绑定方法不适用于getter属性 [英] JavaScript bind method does not work on getter property

查看:84
本文介绍了JavaScript绑定方法不适用于getter属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试这样做:

var c = {
  x: 'other context'
};

var o = {
  x: 'this context',
  get otherContext () {
    alert(this.x);
  }.bind(c)
};

o.otherContext;

但是我收到一个语法错误:

未捕获到的SyntaxError:意外令牌.

用例

您可能会问,为什么我可能想更改吸气剂的上下文.导致我在这里使用的用例涉及创建一个辅助对象,该对象将检索DOM属性.辅助对象是在另一个对象中定义的,该对象持有对我需要其属性的DOM元素的引用.因此,这个辅助对象实际上只是某些DOM方法的代理,我会做类似的事情:

A use-case

You may ask, why I may want to change context on a getter. The use case that led me here dealt with creating a helper object that would retrieve DOM properties. The helper was defined inside another object that held a reference to the DOM element I needed properties from. So, this helper object is really just a proxy for some DOM methods, really, and I would do something like:

var ViewObject = function () {
  this.el = document.getElementById('id');
  
  var proxy = {
    ...
    get left() {
      return this.el.offsetLeft
    }.bind(this)
    ...
  };
};

恕我直言,这是一个非常有效的用例.在其中具有父对象的 this 上下文的环境会很有用.(也许代理功能可能更合适?嗯...我没想到.吸气剂仍然是ES5,代理是ES6,仅由常青树和Edge 13+实现,我认为在ES5的范围内,问题仍然非常严重非常适用.)

IMHO this is a pretty valid use-case. And one where having the parent object's this context would be useful. (Maybe proxy functions may be more adequate? Hmm...I didn't think about that. Still getters are ES5 and proxies are ES6 and only implemented by evergreens and Edge 13+, I think in the scope of ES5 the question still very much applies.)

推荐答案

问题是

The problem is that method syntax doesn't use function expressions. It's a defined syntactic structure.

MethodDefinition [Yield] :

PropertyName [?Yield] ( StrictFormalParameters ) { FunctionBody }

PropertyName[?Yield] ( StrictFormalParameters ) { FunctionBody }

GeneratorMethod [?Yield]

GeneratorMethod[?Yield]

获取 PropertyName [?Yield] ( ) { FunctionBody }

get PropertyName[?Yield] ( ) { FunctionBody }

设置 PropertyName [?Yield] ( PropertySetParameterList ) { FunctionBody }

set PropertyName[?Yield] ( PropertySetParameterList ) { FunctionBody }

PropertySetParameterList :

FormalParameter

由于它不是函数表达式,因此您无权访问函数的方法或属性.

Since it isn't a function expression, you don't have access to the functions methods or properties.

您可以使用 Object.defineProperty .

You can accomplish what you want with Object.defineProperty.

var proxy = { ... };
Object.defineProperty(proxy, 'left', {
  get: function() {
    return this.el.offsetLeft;
  }.bind(this)
});

这篇关于JavaScript绑定方法不适用于getter属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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