1、原型prototype
prototype中有两个属性constructor和__proto__。constructor指向函数自己。同时可以看见prototype中也有__proto__。因为prototype也是一个对象。
var arr1 = [10, 20, 30, 40, 50];
var arr2 = [1, 2, 3, 4, 5];
//给数组添加一个方法,可以计算所有元素的和
arr1.sum = function(){
var num = 0;
for(var i = 0; i < this.length; i++){
num += this[i];
}
return num;
}
alert(arr1.sum());//150
alert(arr2.sum());// arr2.sum is not a function
alert(arr1.sum == arr2.sum);//false
如果想让所有数组队形都拥有求和函数,那么我们的函数需要添加到构造函数的原型上。Array.prototype(原型对象)。
var arr1 = [10, 20, 30, 40, 50];
var arr2 = [1, 2, 3, 4, 5];
Array.prototype.sum = function(){
var num = 0;
for(var i = 0; i < this.length; i++){
num += this[i];
}
return num;
}
alert(arr1.sum());//150
alert(arr2.sum());//15
alert(arr1.sum == arr2.sum);//true
2、 instanceof
instanceof 运算符是用来在运行时指出对象是否是特定类的一个实例。instanceof通过返回一个布尔值来指出,这个对象是否是这个特定类或者是它的子类的一个实例。
__proto__属性,指向构造函数中的prototype属性。
function Person(name, sex){
//添加属性
this.name = name;
this.sex = sex;
}
//通过原型添加方法
Person.prototype.showName = function(){
alert("我的名字叫" + this.name);
}
Person.prototype.showSex = function(){
alert("我是" + this.sex + "的");
}
var p1 = new Person("钢铁侠", "男");
alert(p1 instanceof Person);//true
3、–proto–
function Person(name, sex){
//添加属性
this.name = name;
this.sex = sex;
}
//通过原型添加方法
Person.prototype.showName = function(){
alert("我的名字叫" + this.name);
}
Person.prototype.showSex = function(){
alert("我是" + this.sex + "的");
}
var p1 = new Person("钢铁侠", "男");
alert(p1.__proto__);//[object Object]
alert(p1.__proto__ == Person.prototype);//true
4、总结一下,当你需要理清js中的__proto__和prototype的链接顺序,你只需记住。
(1) 函数对象有__proto__和prototype属性
(2)非函数对象只有__proto__属性
(3)prototype中有__proto__属性。且是Object构造函数创建的
(4)函数对象__proto__指向它的创建者及Function构造函数
(5)Function构造函数__proto__指向它自己
(6)Object对象的prototype中的__proto__是null
5、使用原型链实现继承
for(var funcName in Person.prototype){
Worker.prototype[funcName] = Person.prototype[funcName];
}//遍历对象
6、constructor方法默认返回实例对象,即this。也可以返回其他对象。
/*
ECMA6class类的语法
*/
class Phone{
constructor(size,color){
this.size = size;
this.color = color;
}
show(){
alert(`您选择了${this.color}颜色的,${this.size}GB的手机`);
}
}
class PhoneX extends Phone{
constructor(size,color,type){
//继承父级的属性
super(size,color);
this.type = type;
}
showSelf(){
alert(`您选择了型号为${this.type}的手机`);
this.show();
}
}
var iphoneX = new PhoneX(256, "黑色", "xsMax");
iphoneX.showSelf()