Checking whether toString has been assigned

This question already has an answer here:

  • How do I check if an object has a property in JavaScript? 22 answers

  • obj.hasOwnProperty('toString')


    The result of obj.hasOwnProperty('toString') depends on the way how your toString implementation is created. I did some simple test:

    function A() {
    }
    
    A.prototype.toString = function(){
       console.log("A.toString");
    };
    
    function B() {
       this.toString = function(){
          console.log("B.toString");
       }
    }
    
    var t = [new A(), new B(), new A()];
    
    for(var i=0; i<t.length; i++) {
        var hasOwnToString = t[i].hasOwnProperty("toString");
        console.log(hasOwnToString);
    
        if(hasOwnToString) {
           t[i].toString();
        }
    }
    

    Result:

    false
    true
    B.toString
    false
    

    For A style it's false , but for B style it's true


    You can check to see if the toString function is the same as Object (the object all objects descend from)

    function hasUserPrototype(obj) {
        return Object.getPrototypeOf(obj).toString !== Object.prototype.toString;
    }
    

    See Check if an object has a user defined prototype?

    function Foo() 
    {
    }
    
    // toString override added to prototype of Foo class
    Foo.prototype.toString = function()
    {
        return "[object Foo]";
    }
    
    var f = new Foo();
    
    function Boo() 
    {
    }
    
    var g = new Boo();
    
    function hasUserPrototype(obj) {
        return Object.getPrototypeOf(obj).toString !== Object.prototype.toString;
    }
    
    document.write(hasUserPrototype(f)); // true
    document.write(hasUserPrototype(g)); // false
    链接地址: http://www.djcxy.com/p/27316.html

    上一篇: 检查表单中的输入是否使用nodejs设置

    下一篇: 检查是否已分配toString