0

As output of both the below JS class is same, then what is special here with prototype?

One of the feature of prototype is get rid of duplicate code, in what case this is possible with prototype?

1.

   function Person(name) {
        this.name = name;
        this.sayName = function () {
            console.log(this.name);
        };
    }
    var person1 = new Person("Nicholas");
    person1.sayName();

2.

 function Person(name) {
        this.name = name;
    }
    Person.prototype.sayName = function () {
        console.log(this.name);
    };
    var person1 = new Person("Nicholas");
    person1.sayName();
user584018
  • 10,186
  • 15
  • 74
  • 160

1 Answers1

0

If you assign a property by using prototype then those properties will be shared through out all the instances of the class/constructor which has the particular prototype. But assigning a property using this inside of the constructor will be instance-specific. They cannot be shared with other instances. Each instances will have their own value in it.

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130