谈谈对prototype和__proto__的理解
prototype 原型
每一个函数都有的一个属性。
创建对象的方法(工厂方法)如果将函数添加在prototype原型对象上。
那么通过工厂方法创建出来的对象,可以共享所有prototype原型对象上的函数。
var arr1 = [10, 20, 30, 40, 50];
var arr2 = new Array(1, 2, 3, 4, 5);
Array.prototype.sum = function(){
var res = 0;
for(var i = 0, len = this.length; i < len; i++){
res += this[i];
}
return res;
}
console.log(arr1.sum()); //150
console.log(arr2.sum()); //15
console.log(arr1.sum === arr2.sum); //true
function Person(name, sex) {
//this = new Object();
this.name = name;
this.sex = sex;
//return this;
}
Person.prototype.showName = function () {
console.log(`我的名字叫${this.name}`);
}
Person.prototype.showSex = function () {
console.log(`我的性别是${this.sex}`);
}
//继承Person,实现一个白领类 Worker()
function Worker(name, sex, job) {
Person.call(this, name, sex);
this.job = job;
}
//继承方法
Worker.prototype = Object.create(Person.prototype);
Worker.prototype.showJob = function () {
console.log("我的工作是" + this.job);
}
/*
构造函数构造出来的对象,每一个对象,都拥有一个__proto__的属性。
这个属性,指向,构造出这个对象的构造函数的原型。
原型链 => 构造函数的家族血缘
*/
var p1 = new Person("blue", "男");
console.log(p1.__proto__ == Person.prototype);;
var p2 = new Person("red", "女");
console.log(p2.__proto__ == Person.prototype);
console.log(p1.__proto__.showSex == p2.__proto__.showSex);
console.log(p1)
console.log(p2);
var w1 = new Worker("red", "女", "程序员");
console.log(w1);