Object.defineProperty vs vanilla属性 [英] Object.defineProperty vs vanilla property

查看:115
本文介绍了Object.defineProperty vs vanilla属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到使用的基本情况,请

Considering the basic scenario of usage, do

foo.bar = 'baz';

Object.defineProperty(foo, 'bar', {
  value: 'baz',
  configurable: true,
  enumerable: true,
  writable: true
});

在支持的浏览器中表现完全相同?

behave exactly the same in supported browsers?

我们可以在ES6之前的应用程序中回归vanilla只是因为有利的语法或混合它们而没有任何副作用吗?

Can we fall back to vanilla in pre-ES6 applications just because of favourable syntax or mix both of them without any side effects?

推荐答案

是的,他们的行为相同


  • 没有 bar 属性在 foo (甚至不是继承的),所以创建了一个新的,或

  • 有一个 bar 可写可配置属性设置为 true

  • there is no bar property in foo (not even an inherited one), so a new one is created, or
  • there is a bar property that has the writable and configurable attributes set to true

但是,如果两者都没有给出,那么两者确实会产生略微不同的结果。

However, if neither of those is given, the two indeed produce slightly different results.


  • defineProperty 不考虑继承的属性及其描述符

  • 如果现有(可能是继承的)属性是访问者,则赋值将尝试调用setter(如果不存在则会失败),而 definePropery 将使用数据描述符覆盖该属性(如果是自己的,不可配置的,则会失败)

  • 如果存在inherited属性是一个数据属性,如果 writable 为false,则赋值将失败,如果为true,则创建一个新的属性,如 defineProperty 总是

  • 如果现有的属性是数据属性,如果 writable 为false,则赋值将失败,或者设置新值如果为true,而 defineOwnProperty 将失败iff 可配置为false并且否则覆盖属性。

  • defineProperty does not consider inherited properties and their descriptors
  • If the existing (possibly inherited) property is an accessor, the assignment will try to call the setter (and fail if none exists), while definePropery will overwrite the property with the data descriptor (or fail if it is an own, non-configurable one)
  • If an existing inherited property is a data property, the assignment will fail if writable is false, or create a new own property if true, like the defineProperty always does
  • If an existing own property is a data property, the assignment will fail if writable is false, or set the new value if true, while defineOwnProperty will fail iff configurable is false and overwrite the attributes otherwise.

考虑使用的基本情况

Considering the basic scenario of usage

如果通过基本用法表示没有使用花哨的属性属性,那么它们是等效的。然而你应该只使用简单的作业,因为它们更容易阅读并且执行起来更快。

If by "basic usage" you mean no usage of fancy property attributes, then yes they are equivalent. Yet you should just use the simple assignments, for they are easier to read and faster to execute.


我们可以回到preilla回到vanilla -ES6应用程序

Can we fall back to vanilla in pre-ES6 applications

请注意,ES5附带 defineProperty 的完全支持,所以除非您需要考虑ES5之前的旧浏览器,否则根本不在乎。

Notice that full support of defineProperty comes with ES5, so unless you need to consider pre-ES5 (old IE) browsers you wouldn't care at all.

这篇关于Object.defineProperty vs vanilla属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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