lets have an example ,
var Person = function (name, roll, department) {
this.name = name;
this.roll = roll;
this.dept = department;
}
Person.prototype.calculateTotalMarks = function (bangla, english) {
console.log(bangla + english);
}
var john = new Person("john", 1, "cse");
console.log(john);
john.calculateTotalMarks(50, 50);
var jack = new Person("jack", 2, "eee");
console.log(jack);
jack.calculateTotalMarks(10, 20);
john.calculateTotalMarks(10 , 5);
In the above example Person is the function constructor . Whenever we create our own object john we use new operator which will create an empty object. then function constructor Person will call. We already know in regular function call a new execution context will create and this will point to global object (Window). but by using new operator it will point to our empty object and assign property to our object.
we can declare a method inside function constructor which can be called by the object created using function constructor. But problem is that every object will have a copy of the function . We already know we can inherit method of property inside function prototype.So, we can put method / property in constructor functions property to inherit .
thats why we put that lines,
Person.prototype.calculateTotalMarks = function (bangla, english) {
console.log(bangla + english);
}
then every object of this constructor function will call that method.
john.calculateTotalMarks(20,30);
No comments:
Post a Comment