Object Oriented Programming继承

基于原型的继承
例:
function Foo(){
this.y=2;
}
console.log(typeof Foo.prototype); //"Object"
Foo.prototype.x=1;
var obj3=new Foo();

console.log(obj3.y); //2
console.log(obj3.x); //1

图解:
注意:Object.prototype属性与原型proto是两个概念





prototype属性与原型
例:
function Foo(){}
typeof Foo.prototype; //"object" prototype是函数对象上预设的对象属性,原型是对象的原型,原型通常都是构造器上的(new Foo())上的prototype(对象的)属性,如图解2
Foo.prototype.x=1;
var obj3=new Foo();

图解1:
图解2:
Foo.prototype属性所包含的属性,这里的_proto_属性值为Object.prototype,因此Object.prototype里面的方法,比如说toString、valueOf等方法才会被一般的每一个方法所使用







继承实例
function Person(name,age){
this.name=name;
this.age=age;
}

Person.prototype.hi=function(){
console.log("Hi,my name is"+this.name+",I'm"+this.age+"years old now.");
};

Person.prototype.LEGS_NUM=2;
Person.prototype.ARMS_NUM=2;
Person.prototype.walk=function(){
console.log(this.name+"is walking...");
}

function Student(name,age,className){
this.name=name;
this.age=age;
this.className=className;
}

Student.prototype=Object.create(Person.prototype);
// 为何不写为:Student.prototype=Person.prototype ?因为若是这样子写,那么Student与Person就会指向同一个对象,当我们给Student.prototype增加属性时,同时也给Person.prototype增加同样的属性,所以我们用Object.create方法,这样我们可以向上访问到Person对象,也可以在不影响Person.prototype的前提下创建Student.prototype属性
Student.prototype.constructor=Student;

Student.prototype.hi=function(){
console.log('Hi,my name is'+this.name+',I am'+this.age+"years old now,and from "+this.className+".");
};
Student.prototype.learn=function(subject){
console.log(this.name+'is learning'+subject+'at'+this.className+'.');
};


var bosn=new Student('Bosn',27,'Class 3,Grade 2');
bosn.hi();
console.log(bosn.LEGS_NUM);
bosn.walk();
bosn.learn('math');

猜你喜欢

转载自blog.csdn.net/weixin_39034984/article/details/80723413