Roger
Roger

Reputation: 3

Redefine function's 'toString' and 'valueOf'

I defined a prototype function 'isElement' of Node and I want to make it works like 'div.isElement' return 'true'.

<div id="dom1">someText
    <p>This is p1 of <span class="bold">dom1</span></p>
</div>

Node.prototype.isElement = (function(){
    var result;
    var fn = function(){
        console.log(obj);
        result = (this.nodeType == 1 ? true : false);
        return result;
    };
    fn.toString = fn.valueOf = function(){
        return result;
    };
    return fn;
})();

var dom1 = document.getElementById('dom1');
dom1.isElement();  //true
dom1.isElement;  //true

If the 'dom1' never call the function 'isElement()',then 'dom1.isElement' return 'undefined'. I understand why it return 'undefined',but I want to know how to makes it return 'true' or 'false' when 'isElement()' never be called.

I just want to use it like:

if(dom1.isElement){//do something}

but not like:

if(dom1.isElement()){//do something}

waiting for answers , thanks.

Upvotes: 0

Views: 312

Answers (2)

user1726343
user1726343

Reputation:

You can add a property that has your function as the getter:

Object.defineProperty(Node.prototype, "isElement", {
    get: function() {
        var result = this.nodeType == 1;
        return result;
    }
});

Upvotes: 0

HBP
HBP

Reputation: 16033

As mentioned in the comments, the JavaScript language makes no guarantees that the DOM implementation provides the standard JS object facilities.

That said, if you have determined that your environment always supports these then a getter is called for in this case, effectively you can write a function which is called whenever a specific property value is requested.

Refer to MDN for the details :

Node.prototype.__defineGetter__('isElement', 
  function () { return this.nodeType === 1; });

Test it with your browser at http://jsfiddle.net/L5hBq/

Upvotes: 1

Related Questions