Why can't I redefine a property in a Javascript object?

前端 未结 4 1488
日久生厌
日久生厌 2020-12-08 13:50

I am creating a object using Object.create and I want to add properties to it.

> var o = Object.create({});
undefined

> Object.defineProp         


        
4条回答
  •  轮回少年
    2020-12-08 14:01

    Only when both writable and configurable are false, "Cannot redefine property" will happen.

    If writable or configurable is true, the error will disappear.

    "use strict"
    
    var obj = {};
    
    Object.defineProperty(obj, "name",
    {
       value: "Fundebug",
       writable: false,
       configurable: false
    })
    
    Object.defineProperty(obj, "name",
    {
       value: "云麒"
    }) // “Uncaught TypeError: Cannot redefine property: name”
    

    Therefore, jdphenix and Jonathan are not exactly correct.

提交回复
热议问题