将Object.defineProperty与Angular throws一起使用TypeError:无法分配给#<object>的只读属性(property)

时间:2015-11-19 19:06:29

标签: javascript angularjs defineproperty

我的作用域上有一个对象,我希望该对象有一些非可枚举的属性,但在将可枚举的描述符设置为false后,每当我尝试更改该值时,我得到: &#34; TypeError:无法分配给#&#34;

的只读属性(属性)

...即使我专门将它的可写和可配置描述符设置为true。为什么会发生这种情况,我该怎么做才能解决这个问题? 在非严格模式下,它不会抛出错误,它不会做任何事情。 这应该可以正常工作:MDN ...

代码:

&#13;
&#13;
'use strict'
angular.module('app', []);

angular.module('app').controller('TestingCtrl',['$scope', function($scope){
  var that = this;  
  this.content = { contentArea: {} };
  
  function updateIsEmpty(){
    that.content.contentArea.isEmpty = Object.keys(that.content.contentArea).length === 0;
    console.log(that.content.contentArea)
    console.log(Object.keys(that.content.contentArea));
  }
  
  this.addSomethingToCA = function(val){
    that.content.contentArea.something = val;
    updateIsEmpty();
  };
  this.removeSomethingFromCA = function(){
    delete that.content.contentArea.something;
    updateIsEmpty();
  };
  
  (function init(){
    Object.defineProperty(that.content.contentArea, 'isEmpty', {
      enumerable: false
    , value: true
    , configurable: true
    , writeable: true
    });
   
  })();
}]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="TestingCtrl as testingctrl">
    <button ng-if="testingctrl.content.contentArea.isEmpty === true" 
            ng-click="testingctrl.addSomethingToCA('is weird')">add something</button>
    
    <button ng-click="testingctrl.removeSomethingFromCA()">remove something</button>
    <ul>
      <li ng-repeat="(key, val) in testingctrl.content.contentArea">
        key: {{ key }} 
        val: {{ val }}
      </li>
    </ul>
  </div>
</div>
&#13;
&#13;
&#13;

如果您运行上面的代码段,它会抛出: 类型错误:

 Cannot assign to read only property 'isEmpty' of #<Object>
    at updateIsEmpty (http://stacksnippets.net/js:35:38)
    at removeSomethingFromCA (http://stacksnippets.net/js:46:5)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js:161:190
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js:178:83
    at h.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js:101:273)
    at h.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js:102:48)
    at HTMLButtonElement.<anonymous> (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js:178:65)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js:27:15
    at Array.forEach (native)
    at q (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js:7:255)

1 个答案:

答案 0 :(得分:1)

你有一个错字。属性描述符中的writeable键应为writable

相关问题