Just two common use cases:
1) Quick instance creation
- , :
var Person = function(firstname,lastname) {
this.first_name = firstname;
this.last_name = lastname;
this.sayName = function () {
alert("Hi, my name is " + this.first_name + " " + this.last_name);
};
};
, , , , . , :
var Person = function(firstname,lastname) {
this.first_name = firstname;
this.last_name = lastname;
};
Person.prototype.sayName = function () {
alert("Hi, my name is " + this.first_name + " " + this.last_name);
};
2)
prototype ( ) . :
Array.prototype.forEach = function (callback) {
for (var i = 0; i < this.length; i++) {
callback(this[i], i);
}
};
var arr = [1,2,3,4];
arr.forEach(function(item, index) {
console.log(item);
});
, , .