How to access object prototype in javascript?

后端 未结 5 994
暖寄归人
暖寄归人 2020-11-29 18:57

In all the articles it is written that JavaScript is a prototype-based language, meaning that every object has a prototype (or, more precisely, prototype chain).

So

相关标签:
5条回答
  • 2020-11-29 18:59
    var F = function();
    F.prototype.member1 = 1;
    F.prototype.getClass = F;
    
    var object1 = new F();
    object1.member1 = 2;
    
    console.log(object1.getClass.prototype.member1); // prints 1
    console.log(object1.member1); // prints 2
    
    0 讨论(0)
  • 2020-11-29 19:04
    var F = function(){};
    var object1 = new F();
    alert(object1.constructor === F);
    alert(object1.constructor.prototype === F.prototype);
    
    0 讨论(0)
  • 2020-11-29 19:07
    var F = function();
    F.prototype.member1 = 1;
    var intance = new F();
    console.log(instance['member1']);
    
    0 讨论(0)
  • 2020-11-29 19:19
    var f = function();
    var instance = new f();
    

    If you know name of instance class function, you can simply access prototype as:

    var prototype = f.prototype;
    prototype.someMember = someValue;
    

    If you don't:

    1)

    var prototype = Object.getPrototypeOf(instance);
    prototype.someMember = someValue;
    

    2) or

    var prototype = instance.__proto__;
    prototype.someMember = someValue;
    

    3) or

    var prototype = instance.constructor.prototype; // works only if constructor is properly assigned and not modified
    prototype.someMember = someValue;
    

    For compatibility you can place into your code the following snippet (and use always Object.getPrototypeOf(instance) to return prototype):

    if(!Object.getPrototypeOf) {
    
      if(({}).__proto__ === Object.prototype && ([]).__proto__ === Array.prototype) {
    
        Object.getPrototypeOf = function getPrototypeOf(object) {
          return object.__proto__;
        };
    
      } else {
    
        Object.getPrototypeOf = function getPrototypeOf(object) {
    
          // May break if the constructor has been changed or removed
          return object.constructor ? object.constructor.prototype : void 0;
    
        };
    
      }
    }
    

    UPDATE:

    According to ECMA-262 6th Edition (June 2015) __proto__ property is standardized as additional feature for Web browsers. All latest editions of top browsers supports it now. Read more about __proto__:

    • MDN: Object.prototype.__proto__

    • EDMA-262 6th Edition (June 2015): B.2.2.1 Object.prototype.__proto__

    0 讨论(0)
  • 2020-11-29 19:24

    It looks like

    Object.getPrototypeOf(passedObject);
    

    will work for this, and is compatible with modern browsers.

    Here are the compatibility tables on MDN

    0 讨论(0)
提交回复
热议问题