代码:
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.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');
图解:
获取对象原型的方法:
例:
var obj={x:1};
法一: obj.__proto__ //Object{}
法二: object.getPrototypeOf(obj) //Object{}
法三: function foo(){}
foo.prototype.__proto__===Object.prototype //true ,正因为如此才可以调用 toSting() ,valueOf()方法
注意,并不是所有的对象都有Object.prototype对象,
例1: var obj2=Object.create(null);
obj2.__proto__ //undefined
obj2.toString(); //undefined
并不是所有的函数对象都有Object.prototype对象
例2: function abc(){}
abc.prototype // Object{}
var binded=abc.bind(null);
typeof binded //"function"
binded.prototype //undefined