Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[vue] 说说你对Object.defineProperty的理解 #448

Open
haizhilin2013 opened this issue Jun 22, 2019 · 4 comments
Open

[vue] 说说你对Object.defineProperty的理解 #448

haizhilin2013 opened this issue Jun 22, 2019 · 4 comments
Labels
vue vue

Comments

@haizhilin2013
Copy link
Collaborator

[vue] 说说你对Object.defineProperty的理解

@haizhilin2013 haizhilin2013 added the vue vue label Jun 22, 2019
@maozhuo123
Copy link

Object.defineProperty定义新属性或修改原有的属性;
vue的数据双向绑定的原理就是用的Object.defineProperty这个方法,里面定义了setter和getter方法,通过观察者模式(发布订阅模式)来监听数据的变化,从而做相应的逻辑处理。

@dealdot
Copy link

dealdot commented Apr 21, 2021

Object.defineProperty定义新属性或修改原有的属性;
vue的数据双向绑定的原理就是用的Object.defineProperty这个方法,里面定义了setter和getter方法,通过观察者模式(发布订阅模式)来监听数据的变化,从而做相应的逻辑处理。

为何大家都说数据双向绑定原理,这里应该是说响应式吧,双向绑定不是v-model这样的才算吗?

@Gcalolin
Copy link

Gcalolin commented Aug 25, 2021

Object.defineProperty 基础用法:

Object.defineProperty(obj, 'propertyName', {
     value: xxx,
    writable: true, // 默认是可写的
    configurable: false, // 默认是不可配置的,删除或更改任何属性都会失败
    enumerable: false, //  默认是不可枚举的,for...in 遍历不到
   get() {},
  set(newVal) {}
})

vue2 通过遍历组件的data函数返回的对象的所有属性,对每个属性都进行Object.defineProperty的 getter setter, 在getter时收集依赖,setter时触发watcher 更新依赖

@hyj443
Copy link

hyj443 commented Oct 20, 2021

Object.defineProperty 定义一个对象的属性,三个参数都必填,第三个参数是属性描述符对象

经过Object.defineProperty()定义的属性,再次调用Object.defineProperty()定义相同的属性,会报错 Uncaught TypeError: Cannot redefine property

而且你通过.key修改属性值,也无法修改。因为Object.defineProperty()定义的属性是不可修改的。

但是,一开始就存在的属性,可以通过.key或Object.defineProperty()重复修改

ES5有两种属性,数据属性和访问器属性

数据属性有4个属性描述符来描述它:

  1. Configurable 是否可配置(能否删除,能否修改属性的描述符),能否改成访问器属性,默认为true
  2. Enumerable 是否可枚举,默认为true
  3. writable 默认为false,只有true时,value才能被赋值语句修改
  4. Value 该属性的属性值,默认为undefined

访问器属性

访问器属性不包含数据值,包含getter和setter函数(不是必须,默认为undefined)

当一个属性设置了 get 和 set,它就是一个访问器属性

getter在读取访问器属性时被触发,setter在修改访问器属性时被触发

访问器属性只能通过Object.defineProperty()来定义

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
vue vue
Projects
None yet
Development

No branches or pull requests

5 participants