面试题:(考察Object.defineProperty(obj,prop,descriptor) 的get方法)

来源:互联网 发布:php教程百度云 编辑:程序博客网 时间:2024/05/01 20:11

参考链接1 javascript学习(九)对象属性的特性

参考链接2https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty


案例1:

var person = {};Object.defineProperty(person, "name", {    value:"Tom",    writable:false,    enumerable:false,    configurable:false});console.log(person.name);   //Tomperson.name = "Linda";console.log(person.name);   //Tom

案例2:

var person = {};Object.defineProperty(person, "name", {    value:"Tom",    writable:true,    enumerable:false,    configurable:true});console.log(person.name);   //Tomperson.name = "Linda";console.log(person.name);   //Linda

图解:
这里写图片描述

案例3:官方文档解释的太好了!!!

Writable attribute

When the writable property attribute is set to false, the property is said to be “non-writable”. It cannot be reassigned.

var o = {}; // Creates a new objectObject.defineProperty(o, 'a', {  value: 37,  writable: false});console.log(o.a); // logs 37o.a = 25; // No error thrown// (it would throw in strict mode,// even if the value had been the same)console.log(o.a); // logs 37. The assignment didn't work.

As seen in the example, trying to write into the non-writable property doesn’t change it but doesn’t throw an error either.


以上内容作为个人学习记录使用,仅供参考,不足之处,烦请告知。

0 0
原创粉丝点击