1.Function对象和Object对象的原型指向关系:
1> function定义的函数对象的proto属性指向Function对象的prototype对象。
2> 非function定义的对象的proto属性指向创建它的构造函数的prototype对象。
3> Object的prototype对象的proto指向null。
4> Function的prototype对象的proto指向Object对象的prototype对象。
测试代码如下:
console.log(Object.prototype);
console.log(Object.prototype.constructor === Object);//true
console.log(Object.prototype.__proto__ === null);//true
console.log(Object.__proto__ === Function.prototype);//true
console.log(Function.prototype);
console.log(Function.prototype.constructor === Function);//true
console.log(Function.prototype.__proto__ === Object.prototype);//true
console.log(Function.__proto__ === Function.prototype);//true
2.根据组合继承理解原型链,代码如下:
//父类
function Person(name,age){
if(this instanceof Person){
this.name = name; this.age = age;
}else {
Person.call(this,name,age);
}
}
Person.prototype.say = function(){
console.log('我叫' + this.name +',今年' + this.age + '岁了!')
}
//子类
function Student(name,age,gride){
if(this instanceof Student){
Person.call(this,name,age);
}else {
Student.call(this,name,age,gride);
}
}
Student.prototype = new Person();
Student.prototype.constructor = Student;
Student.prototype.say = function(){
console.log('我叫' + this.name +',今年' + this.age + '岁了,考试考了' + this.gride + '分!');
}
var stu = new Student('chping',23,100);
stu.say();