96
Edit 2016.03: Object.observe
is deprecated and removed in Chrome 50
编辑2016.03:在Chrome 50中弃用并删除了Object.observe
Edit 2014.05: Object.observe
was added in Chrome 36
编辑2014.05:在Chrome 36中添加了Object.observe
Chrome 36 ships with native Object.observe
implementation that can be leveraged here:
Chrome 36附带本机Object.observe实现,可在此处使用:
myObj = {a: 1, b: 2};
Object.observe(myObj, function (changes){
console.log("Changes:");
console.log(changes);
debugger;
})
myObj.a = 42;
If you want it only temporarily, you should store callback in a variable and call Object.unobserve
when done:
如果只是暂时需要它,则应将回调存储在变量中,并在完成后调用Object.unobserve:
myObj = {a: 1, b: 2};
func = function() {debugger;}
Object.observe(myObj, func);
myObj.a = 42;
Object.unobserve(myObj, func);
myObj.a = 84;
Note that when using Object.observe
, you'll not be notified when the assignment didn't change anything, e.g. if you've written myObj.a = 1
.
请注意,使用Object.observe时,如果分配没有改变任何内容,您将不会收到通知,例如如果你写了myObj.a = 1。
To see the call stack, you need to enable "async call stack" option in Dev Tools:
要查看调用堆栈,您需要在Dev Tools中启用“异步调用堆栈”选项:
Original answer (2012.07):
原始答案(2012.07):
A console.watch
sketch as suggested by @katspaugh:
@katspaugh建议的console.watch草图:
cOnsole= console || {}; // just in case
console.watch = function(oObj, sProp) {
sPrivateProp = "$_"+sProp+"_$"; // to minimize the name clash risk
oObj[sPrivateProp] = oObj[sProp];
// overwrite with accessor
Object.defineProperty(oObj, sProp, {
get: function () {
return oObj[sPrivateProp];
},
set: function (value) {
//console.log("setting " + sProp + " to " + value);
debugger; // sets breakpoint
oObj[sPrivateProp] = value;
}
});
}
Invocation:
调用:
console.watch(obj, "someProp");
Compatibility:
兼容性:
- In Chrome 20, you can paste it directly in Dev Tools at runtime!
- 在Chrome 20中,您可以在运行时将其直接粘贴到Dev Tools中!
- For completeness: in Firebug 1.10 (Firefox 14), you have to inject it in your website (e.g. via Fiddler if you can't edit the source manually); sadly, functions defined from Firebug don't seem to break on
debugger
(or is it a matter of configuration? please correct me then), but console.log
works.
- 为了完整性:在Firebug 1.10(Firefox 14)中,您必须将其注入您的网站(例如,如果您无法手动编辑源,请通过Fiddler);遗憾的是,从Firebug定义的函数似乎没有在调试器上中断(或者它是配置问题?请纠正我),但console.log工作。
Edit:
编辑:
Note that in Firefox, console.watch
already exists, due to Firefox's non-standard Object.watch
. Hence in Firefox, you can watch for changes natively:
请注意,在Firefox中,由于Firefox的非标准Object.watch,console.watch已经存在。因此,在Firefox中,您可以本地监视更改:
>>> var obj = { foo: 42 }
>>> obj.watch('foo', function() { console.log('changed') })
>>> obj.foo = 69
changed
69
However, this will be soon (late 2017) removed.
但是,这将很快(2017年底)删除。