Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Overriding property (not methods) inside an Object

Tags:

javascript

Let us explain the question with an example. I have a text box. The textbox (every textbox) has a property called 'value'. I want to over ride that textbox.value and comeup with and new thing. When the text in textbox is 'ranjan' then the textbox.VALUE property returns 'ranjan'. Now I want to thus overwrite this so that when you type textbox.VALUE you get a different thing say for example, RaNjAn or say, Mr. Ranjan or whatever.

We can over ride methods using Object.PROTOTYPE property. But how can we do it for non-function objects inside object for example the 'value' property in this case.

If i need to make the question more clear, please mention.

Regards - Ranjan.

like image 891
Ranjan Sarma Avatar asked Sep 21 '12 12:09

Ranjan Sarma


1 Answers

You can define custom properties for your element using Object.defineProperty

If you have a case where you need to get the value of an element as Mr. <value> for example, then this approach will be useful. Overriding standard properties may not be such a good idea.

Demo: http://jsfiddle.net/zvCGw/2/

Code:

var foo = document.getElementById('foo');

Object.defineProperty(foo, "xvalue", {
    get: function() {
        return 'Mr. ' + foo.value;
    },
    set: function(_newValue) {
        foo.value = _newValue;
    }
});

foo.xvalue = 'Hello';

alert(foo.xvalue);
like image 133
techfoobar Avatar answered Nov 10 '22 16:11

techfoobar