• Blogs (9)
    • 📱 236 - 992 - 3846

      📧 jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • JavaScript: object and prototype

    Blogs20142014-04-10


    JavaScript: object and prototype

    When writing a construct function, the default properties it owns including:

    • prototype
    • arguments
    • name
    • length
    • contractor
    • apply, bind, call, caller
    • hasOwnProperty, isPropertyOf, toString, valueOf…

    So does an object have an prototype property? It has not. Instead of ‘prototype’, it has the secret ’__proto__’ property to related to its contractor’s prototype object. The following is some of my tests:

    var o = {}
    o.constructor // function Object() { [native code] }
    o.constructor.prototype //Object {}
    o.constructor.prototype.constructor //function Object() { [native code] }
    o.constructor.prototype.constructor.prototype //Object {}
    
    var i, hasOwn = Object.prototype.hasOwnProperty;
    
    for (i in o) { if (hasOwn.call(o, i)) { console.log(i+ ":"+ o[i]); }}
    //undefined
    o.name='abc';
    for (i in o) { if (hasOwn.call(o, i)) { console.log(i+ ":"+ o[i]); }}
    // name:abc
    for (i in o) { console.log(i+ ":"+ o[i]); } //name:abc
    
    o.toString()
    "[object Object]"
    o instanceof Object  // true
    typeof o  //"object"
    
    o.__proto__ // Object {}
    o.constructor.prototype === o.__proto__ // true

    instanceof vs typeof

    the ’instanceof’ and ’typeof’ are 2 ways used to judge variables, here is the difference I got from stackoverflow:

    • Use instanceof for custom types
      obj instanceof Person
    • Use typeof for simple built in types
      typeof variable === ‘undefined’ typeof variable === ‘number’ typeof variable === ‘string’
    • Use instanceof for complex built in types