如何在 JavaScript 中填充属性?

发布于 2024-12-15 13:21:31 字数 332 浏览 4 评论 0原文

给定一个将在浏览器中添加前缀的事件属性,我想创建一个polyfill,使其显示为无前缀。

例如,接口 FooEvent 有一个属性 webkitBar,我希望将其显示为 bar,以便处理程序可以编写为 onFoo = function(e) { console.log(e.bar); }

我笨拙的最初猜测是向原型中注入一些东西 FooEvent.prototype.getBar = function() { return this.webkitBar; }。但是,我不确定如何。

Given an attribute on an event that will be browser prefixed, I'd like to create a polyfill that makes it appear unprefixed.

E.g. the interface FooEvent has an attribute webkitBar that I'd like to make appear as just bar so that handlers could be written as onFoo = function(e) { console.log(e.bar); }

My clumsy initial guess is to inject something into the prototype FooEvent.prototype.getBar = function() { return this.webkitBar; }. But, I'm not certain how.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

冬天的雪花 2024-12-22 13:21:31

仅限 ES5(和 IE8)

Object.defineProperty(FooEvent.prototype, "bar", {
  get: function () {
    return this.webkitBar;
  },
  configurable: true
});

请注意扩展宿主对象。 (FooEvent 是一个宿主对象)具有未知的副作用,并且是一大堆未定义的行为。

我推荐静态包装器

var eventUtil = {
  getBar: function (ev) {
    return ev.webkitBar;
  }
}

function handler (e) {
  var bar = eventUtil.getBar(e);
}

ES5 only (and IE8)

Object.defineProperty(FooEvent.prototype, "bar", {
  get: function () {
    return this.webkitBar;
  },
  configurable: true
});

Be warned that extending host objects. (FooEvent is a host object) has unknown side effects and is a big bag of undefined behaviour.

I'd recommend static wrappers

var eventUtil = {
  getBar: function (ev) {
    return ev.webkitBar;
  }
}

function handler (e) {
  var bar = eventUtil.getBar(e);
}
七度光 2024-12-22 13:21:31

您可以向事件注册一个“第一个”处理程序来进行转换:

function adaptsBar(e) {
  e.bar = e.webkitBar;
}

You could register a "first" handler to the event to do the transformation:

function adaptsBar(e) {
  e.bar = e.webkitBar;
}
蓝眸 2024-12-22 13:21:31

这是帮助您入门的好资源。

http://addyosmani.com/blog/writing-polyfills/

This is a good resource to get you started.

http://addyosmani.com/blog/writing-polyfills/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文