til
  • README
  • Software Development Roles
  • solid
  • README
    • service-worker
  • docker
    • arg
    • 更新docker版本
  • editor
    • vscode
    • Creating a VS Code Theme
  • english
    • words
  • front-end
    • ==
    • ECMAScript
    • IIFE
    • Label
    • basic
    • html.js.css渲染顺序
    • npm-vs-yarn
    • obj-delete-key-value
    • react
    • split-join-and-replace
    • video
    • 前端自检清单
    • 递归及去重
    • css
      • css换肤
      • flex
      • list
      • nth-child和nth-of-type区别
      • padding
      • position
      • 层叠上下文
      • 层叠样式(+)
      • 正方形
      • 语义化标签
    • dom
      • DOCTYPE
      • HEAD
      • 修改document
      • 自定义表单验证
    • electron
      • basic
    • es6
      • basic-type
      • basic
      • prototype-example
      • defineProperty
      • understanding-es6
        • 0.introduction
        • Appendix A: Smaller Changes
        • Appendix B: Understanding ES7
        • Block-Binding
        • Proxies&Reflection
        • class
        • 解构赋值
        • function
        • improved-array
        • iterators&generators
        • modules
        • object
        • promise
        • Map&Set
        • symbol
    • images
      • 前端角度看图片
    • interview_case
      • lexical_scope
      • redux和localstroage存储位置
    • javascript
      • fuck-the-js
      • js-engine-work
      • js原生操作dom
      • what-is-function-program
      • 执行上下文
      • articles
        • JavaScript中使用函数组合
        • JavaScript中的依赖注入
        • JavaScript作用域链中的标识符解析和闭包
        • JavaScript是何如工作的--概述
        • JavaScript深拷贝
        • JavaScript的全局变量是如何工作的
        • js继承常见的误解
        • node12&chrome中7个新的提案功能
        • 你真的懂JavaScript吗
      • date
        • index
      • engines
        • basic
        • JavaScript引擎基础:外形和内联缓存
        • v8中推测性优化的介绍
        • 优化原型
        • 更快的异步功能和promise
      • events
        • baisc
        • 事件冒泡和捕获
        • 定义事件
        • 页面生命周期
      • higher-order-function
        • curry
        • monad
      • module
        • basic
        • main&module
      • objects
        • iterator
        • spread
        • examples
          • iterator
      • performance
        • blocking-css
        • cache
      • prototype
        • Property-Descriptors
        • basic
        • prototype-shadow
      • you-dont-known-js
        • async&performance
          • Chapter 1: Asynchrony: Now & Later
          • Chapter 2: Callbacks
          • Chapter 3: Promises
          • Chapter 4: Generators
        • scope & closures
          • apA
          • apB
          • apC
          • apD
          • chapter1-what-is-scope
          • chapter2-lexical-scope
          • chapter3-function-vs-block-scope
          • chapter4-hoisting
          • chapter5-scope-closure
        • this & object prototypes
          • chapter1-this-or-that
          • chapter2-this-make-sense
          • chapter3-objects
          • chapter4-mixing(up)-class-object
          • chapter5-prototype
          • chapter6-behavior-delegation
        • types&grammer
          • Chapter1-Types
          • Chapter2-Values
          • Chapter3-Natives
          • Chapter4-coercion
          • Chapter5-grammer
        • up & going
          • chapter1-into-programming
          • chapter2-into-javascript
          • chapter3-into-YDKJS
    • mobile
      • iPhone分辨率终极指南
    • npm
      • arguments
      • build
    • react-native
      • prop-methods
    • react
      • PropTypes
      • basic
      • codebase-overview
      • component-element-instance
      • context
      • how-to-known-component-is-func-or-class
      • overview
      • react16.9
      • react18计划
      • react的设计原则
      • reconciliation
      • setState
      • useMemo
      • why-do-we-write-super-props
      • 从头实现一个react
      • concurrent
        • 引入并发模式(仅试验)
      • conf
        • conf-2019
      • events
        • 合成事件概述
      • hooks
        • custom-hook
        • effect-hook
        • hooks-api
        • intro
        • overview
        • rules
        • state-hook
        • hooks-vs-class
          • thinking-in-react-hooks
      • overreact
        • Development模式是如何工作的
        • How-Does-setState-Know-What-to-Do
        • Why-Do-React-Elements-Have-a-$$typeof-Property
        • Why-Do-React-Hooks-Rely-on-Call-Order
        • how-to-known-component-is-func-or-class
        • preparing-tach-talk-motivation
        • react作为ui运行
        • things-i-dont-known-as-2018
        • ui-element-problem-and-build-yourself
        • why-do-we-write-super-props
        • 一份完整的useEffect指南
        • 为什么X不是Hook
        • 函数组件与类有什么不同?
        • 演讲准备2-what-why-how
        • 编写弹性组件
        • 让setInterval在React-Hooks中为声明式
      • practice
        • render
      • react-dom
        • basic
      • react-redux
        • apiv7.1-hooks
        • connect
        • shallow-equal
      • redux
        • applyMiddleware
        • applyMiddleware2-细节
        • example
    • regex
      • index
    • stories
      • 数组下标
      • 阻止事件冒泡
    • svelte
      • compile-svelte-in-your-head-1
      • compiler-overview
      • parser
        • 写一个解析器-JavaScript的JSON解析器
    • turbopack
      • basic
    • typescript
      • interface和type的区别
    • webpack
      • hash
      • webpack4-for-react
      • webpack4
      • webpack4to5
      • babel
        • babel-parser和acorn的区别
        • babel.7.11
        • family
        • react16.14使用new-transform
        • update-to-7
    • pdf
      • deep-js
        • basic
      • react
        • reintroducing
  • git
    • capital
    • emoji
  • http
    • http2.0
    • response
  • rails
    • api
    • flash
    • middleware-vs-metal
    • model
    • performance
    • routes
    • environment
      • error
    • patterns
      • service
    • sidekiq
      • params
    • deploy
      • capistrano
        • ssh
  • ruby
    • self
    • net
      • http请求携带cookie
  • server
    • ss
    • ssh
    • user
    • crawler
      • puppeteer
    • nginx
      • domain-without-80
      • nginx节省带宽
  • sql
    • rails
    • search
Powered by GitBook
On this page
  • writable
  • configurable
  • enumerable
  • getter & setter
  • 其他实用方法
  • Prevent Extensions
  • Seal
  • freeze
  1. front-end
  2. javascript
  3. prototype

Property-Descriptors

其实主要就是针对(writable, enumerable, configurable).

获取属性描述可通过Object.getOwnPropertyDescriptors(you object)。

var myObject = {
    a: 2
};

Object.getOwnPropertyDescriptor( myObject, "a" );
// {
//    value: 2,
//    writable: true,
//    enumerable: true,
//    configurable: true
// }

针对于这个属性特性,需要提示的就是字面量创建的对象属性和defineProperty创建的对象属性,是不同的,字面量创建的对象属性的特性都是true, defineProperty恰恰相反.

writable

这个特性主要负责对象属性是否可变。

let obj = {}
Object.defineProperty( obj, "a", {
    value: 2,
    writable: false, // not writable!
    configurable: true,
    enumerable: true
} );

obj.a = 3;

obj.a; // 2

由上代码可以看出,赋值无效。 如果在严格模式下,赋值会报错。

configurable

这个就是控制是否可配置,如果这个属性是true,那就可以使用defineProperty对属性进行配置。

var myObject = {
    a: 2
};

myObject.a = 3;
myObject.a;                    // 3

Object.defineProperty( myObject, "a", {
    value: 4,
    writable: true,
    configurable: false,    // not configurable!
    enumerable: true
} );

myObject.a;                    // 4
myObject.a = 5;
myObject.a;                    // 5

Object.defineProperty( myObject, "a", {
    value: 6,
    writable: true,
    configurable: true,
    enumerable: true
} ); // TypeError

可以看出来,报错了。如果configurable: false,那么就不可以进行配置了。而且不管是否为严格模式,都会报错。并且注意,这个是一个 单项操作,不可逆

同时,delete操作也是通过confirurable 来进行控制的。

var myObject = {
    a: 2
};

myObject.a;                // 2
delete myObject.a;
myObject.a;                // undefined

Object.defineProperty( myObject, "a", {
    value: 2,
    writable: true,
    configurable: false,
    enumerable: true
} );

myObject.a;                // 2
delete myObject.a;
myObject.a;                // 2

可以发现,删除属性失败,因为configurable是false

我们知道,Object.freeze可以冻结对象,就是不能操作。可以看下

let o = {name: 'xiaohesong'}
Object.getOwnPropertyDescriptors(o)
Object.freeze(o)
Object.getOwnPropertyDescriptors(o)

可以发现,上面的freeze方法导致对象的writable和configurable改成了false.

enumerable

这个是控制属性是否显示,例如for .. in循环中,false便不会显示。⚠️ for(let i in obj)是根据enumerable来显示,in操作不管enumerable,只是单纯的查找

  • in & hasOwnProperty

in是检索整个原型链的key(property),hasOwnProperty仅仅检索当前对象的key(property),不会蔓延到原型链上层去查找。

4 in [2,4,6] // false, 因为检索的是key,不是value

下面再来看看enumerable

var myObject = { };

Object.defineProperty(
    myObject,
    "a",
    // make `a` enumerable, as normal
    { enumerable: true, value: 2 }
);

Object.defineProperty(
    myObject,
    "b",
    // make `b` NON-enumerable
    { enumerable: false, value: 3 }
);

myObject.b; // 3
("b" in myObject); // true
myObject.hasOwnProperty( "b" ); // true

// .......

for (var k in myObject) {
    console.log( k, myObject[k] );
}
// "a" 2

可以发现这个myObject.b是存在的,可访问的,但是因为enumerable: false导致for .. in不显示出b属性。 这是因为enumerable表示只包含可以被枚举的属性。

可不可以枚举,可以判断出来,如下:

var myObject = { };

Object.defineProperty(
    myObject,
    "a",
    // make `a` enumerable, as normal
    { enumerable: true, value: 2 }
);

Object.defineProperty(
    myObject,
    "b",
    // make `b` non-enumerable
    { enumerable: false, value: 3 }
);

myObject.propertyIsEnumerable( "a" ); // true
myObject.propertyIsEnumerable( "b" ); // false

Object.keys( myObject ); // ["a"]
Object.getOwnPropertyNames( myObject ); // ["a", "b"]

很明显的看到, propertyIsEnumerable可以针对某个属性进行判断,Object.keys获取的是可枚举的属性列表, getOwnPropertyNames获取的是所有的属性名称。

所以可以知道两点:

  • in vs hasOwnProperty

    hasOwnProperty查找的是当前对象的属性,不会提升到prototype chain查找。in则会查找整个原型链.

  • Object.keys vs getOwnPropertyNames

    这两个都只是作用在当前的对象上,不会遍历原型链。 Object.keys返回的是可枚举的属性名称列表,Object.getOwnPropertyNames返回的是所有的属性名称,无论是否可以枚举。

  • [GET]

对象调用属性时,某人优先调用get方法。

let obj = {
  a: 'normal-a',
  get a() {
    return 'get-a'
  }
}
obj.a // 'get-a'
obj.a = 'reset-a'
obj.a // 'get-a'

上面的代码很明了,优先调用定义的get方法。

let obj = {
  a: 'normal-a',
  get a() {
    return this._a_
  },
  set a(val) {
    this._a_ = val;
  }
}

obj.a // undefined
obj.a = 'reset-a'
obj.a // reset-a

注意到了_a_了吧,不用多想,没啥特别的意思,就是按照约定,加下划线,你也可以用其他的来表示,但是不能用a,否则会循环到堆栈溢出。

其他实用方法

Prevent Extensions

这个属性是关闭后续拓展,对原有属性保留操作(writable, configurable, enumerable 均为 true)。

var myObject = {
    a: 2
};

Object.preventExtensions( myObject );
myObject.a = 3
myObject.b = 3;
myObject.a // 3
myObject.b; // undefined

使用Object.defineProperty也不行.

严格模式下,myObject.b会报错。

Seal

这个是在preventExtensions方法的基础上,设置所有现有属性Objconfirurable: false, 使其封闭, 不可配置,不可删除, 但是可以修改,因为writable是`true. 由上面知道,delete由configurable`控制。

freeze

上面有提到过freeze是使configurable和writable都为false.其实就是在seal的基础上,使所有存在的属性的writable为false。

PreviousprototypeNextbasic

Last updated 6 years ago

getter & setter