What is the word prototype used for in Javascript?

This question already has an answer here:

  • How does JavaScript .prototype work? 21 answers

  • The prototype chain is how you associate a method with a given type instead of just a specific instance of an object. It's beneficial for performance reasons since you don't have to redefine the method for every instance since it's defined once at the type level.

    Example using prototype:

    var car = function(){
    };
    
    car.prototype.start= function(){
    };
    
    var myCar = new car();//all car objects will have the start function defined.
    

    Example where prototype is not used:

    var car = {};
    car.start = function(){}; 
    

    The biggest difference here is that the second example doesn't take advantage of the prototype, and is instead just tacking on a start method to the current instance only. In the first example all created instances will have access to the start method.

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

    上一篇: 如何处理javascript对象

    下一篇: Javascript中使用的原型是什么?