Accessing Javascript object prototype

This question already has an answer here:

  • How does JavaScript .prototype work? 21 answers

  • You do have access to the prototype property, but it is only present on Function s.

    var car = {
        Make: 'Nissan',
        Model: 'Altima'
    }; 
    

    This is the same as:

    var car = new Object();
    car.Make = 'Nissan';
    car.Model = 'Altima'; 
    

    So, car.__proto__ === Object.prototype .

    And car.prototype === undefined as the prototype property is only present on Function s (as I already said).

    function Car() {
        this.Make = 'NISSAN';
        this.Model = 'Atlanta';
    }
    

    Here Car.prototype points to an instance of Object because Car is a function and when function declarations are evaluated their prototype is set to an instance of Object .

    Car.prototype.Year = 2014; //all Car *instances* will have a Year property set to 2014 on their prototype chain.
    
    var c = new Car(); //create an instance
    console.log(c.Year); //2014
    

    Overriding a method present on the prototype chain for an object is as simple as creating a corresponding method on the object:

    var myObject = new Object();
    myObject.toLocaleString = function() {
      //my own implementation
    };
    

    You probably want to modify the constructor function prototype:

    function Car(year, make, model) {
      this.year  = year;
      this.make  = make;
      this.model = model;
    }
    
    Car.prototype.toLocaleString = function() {
      return [this.year, this.make, this.model].join(' ');
    };
    
    var civic = new Car(2014, 'Honda', 'Civic');
    civic.toLocaleString(); // => "2014 Honda Civic"
    

    This MDN article on Object.prototype might be helpful.

    链接地址: http://www.djcxy.com/p/30066.html

    上一篇: 无法设置未定义JS的属性“名称”

    下一篇: 访问Javascript对象原型