Javascript 如何使用object.defineProperty通知json对象值更改?
我知道如何使用object.defineProperty通知对象中的值更改,但我想知道如何通知json对象值更改 更多关于这个 为strore创建新实例并将值设置为price时,notifyPriceChange将调用Javascript 如何使用object.defineProperty通知json对象值更改?,javascript,Javascript,我知道如何使用object.defineProperty通知对象中的值更改,但我想知道如何通知json对象值更改 更多关于这个 为strore创建新实例并将值设置为price时,notifyPriceChange将调用 function store(){ var price Object.defineProperty(this, "price", { get : function(){ return price;
function store(){
var price
Object.defineProperty(this, "price",
{
get : function(){
return price;
},
set : function(newValue){
price = newValue;
notifyPriceChange();
},
enumerable : true,
configurable : true
});
}
我想在这里做同样的事情
var obj = jQuery.parseJSON( '{"price":"120"}' );
obj.price = "John"
当我将值设置为price时,表示我要通知。如何做到这一点?对JSON的引用与问题无关 您的问题是您有一个对象
obj
,该对象具有一个现有属性price
,如果该值发生更改,您希望能够建立对函数的调用
您的存储过程可以调整如下:
function store () {
var price;
// if this.price exists, save its value and delete it
if (this.hasOwnProperty ('price')) {
price = this.price;
delete this.price;
}
// Now define the price property specifying the callback on change
Object.defineProperty (this, "price", {
get : function(){
return price;
},
set : function (newValue) {
price = newValue;
notifyPriceChange ();
},
enumerable : true,
configurable : true
});
}
// call as follows :
var obj = jQuery.parseJSON ('{"price":"120"}');
store.apply (obj); // establish new price property with callback on change
obj.price = "John"
本质上,我们删除现有属性,保存其值,然后使用我们想要的属性创建属性。我们想知道您尝试了什么,您在说什么“JSON对象”?JSON是adata交换格式,因此是JavaScript中的字符串。是否要通知字符串?(不管这意味着什么)。不清楚你想做什么,知道什么。请提供一些示例代码。当我有多个这样的实体时,这是怎么回事。var obj=jQuery.parseJSON(“{”price:“120”,“name:“John”,“amount:“12”}”);在这种情况下,金额和价格的处理方式是一样的。是的,但价格、金额等条目只是一种情况。这些条目由用户端提供。因此,他们也可能会以不同的方式命名,也可能会有更多的条目,如(数量、数字、时间)。我们应该为这些情况做些什么?