Break points on User Defined object properties in JavaScript

旧街凉风 提交于 2019-12-12 06:33:15

问题


Break points on User Defined object properties in javascript

Hello

Is there is any JavaScript debugging tool or addon that helps to put break points on User Defined object properties.

Eg:

I have a JavaScript Object Literal

var TextBox = { color:"gray", size:"100px", border:true }

Here is my code that does the modification

function foo(){ TextBox["color"] = "blue"; }

I am looking for putting a breakpoint on TextBox.color so that when the property is modified I could find who is doing the modification or which function does the alteration.

It should also break when TextBox.color = null; or delete TextBox.color;

Is this feature already available in firebug or chrome developer tool?

I have already seen breakpoints for html element removal , attribute modification but not for user defined object properties.

Thanks.


回答1:


Have a look at the magic getters and setters that some browsers support: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters

You should be able to define a setter and put a breakpoint in it.

Probably best to keep these out of production code for compatibility reasons, but they're the only practical way to debug certain problems.




回答2:


Use something like this:

(function() {
    var obj=TextBox; var realValue = obj.color; 
    Object.defineProperty(obj, 'color', { 
        set: function(newValue) { debugger; realValue = newValue; },
        get: function() { debugger; return realValue; } 
    });
})();

and simply run it in your browsers console.



来源:https://stackoverflow.com/questions/12577535/break-points-on-user-defined-object-properties-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!