Defining a Javascript prototype

后端 未结 5 1763
陌清茗
陌清茗 2020-11-22 10:05

What are the functional differences between the following two Javascript prototypes, and are there any benefits for choosing one over the other?

Option 1:

5条回答
  •  长发绾君心
    2020-11-22 10:46

    The second one will overwrite person.prototype with the object.

    Method one:

    Object.toString=function(){
      return "Object to string";
    }
    var Person = function(){
    };
    Person.toString=function(){
      return "Person to string";
    }
    Person.prototype.sayName=function(){}
    console.log(Person.prototype.constructor.toString());// "Person to string"
    

    Method two:

    Object.toString=function(){
      return "Object to string";
    }
    var Person = function(){
    };
    Person.toString=function(){
      return "Person to string";
    }
    Person.prototype = {
      sayName:function(){}
    }
    console.log(Person.prototype.constructor.toString());// "Object to string"
    

提交回复
热议问题