想讲个题外话,为什么我提到这个名字总能想到日本的一部电影《寄生兽》? exm?
// 直接调用this指向window,用new不是
function Father(name,age){
this.name = name;
this.age = age;
}
// 创建一个父类对象
var f = new Father('ilv',22);
Father.prototype.hi = function(){
console.log("hello "+this.name,this.age);
}
Father.prototype.salary = 9999;
f.hi();
function Child(name,age,gender){
Father.apply(this,arguments);
this.gender = gender;
}
//var c = new Child('mmc',18,'M');
//console.log(c.name,c.gender);
// 构造器继承方法无法获取父类原型上的方法
//c.hi(); //报错,没有这个方法
// Object.create(arg);
// 创建一个空对象,并且对象的原型指向参数
// 思考为什么不能直接? Child.prototype = Father.prototype ?
Child.prototype = Object.create(Father.prototype);
Child.prototype.constructor = Child;
var c = new Child('mmc',18,'M');
c.hi(); /// 9999
console.log(c.salary);
Child.prototype.hi = function(){
console.log(this.name,this.age,this.gender);
}
// 重写父类方法
c.hi();
console.log(f.__proto__ === Father.prototype); // true
console.log(typeof Father.prototype.__proto__); // Object
console.log(Child.prototype.__proto__ === Father.prototype); // true
// 至此,原型链的含义也就出来了..
console.log(c instanceof Father); //true
console.log(new Object() instanceof Array); //false
// 左边对象 右边函数(构造器)
// 左边不是对象直接返回false
//怎么判读? 右边的prototype属性是否出现在左边的对象的原型链上
/*
解释:直接Child.prototype = Father.prototype 。
当我们给child prototype加些属性后,father也会加上
*/
// 并不是所得函数都有prototype对象属性:bind()