实习日志-5(javascript)
深入prototype之实现继承
由于javascript不像某些面向对象语言具有继承的语法,但是我们在很多时候又需要用到继承,所以,这就需要用到prototype chainning(原型链)来实现继承。
例1
function A(){
this.name = 'A';
this.toStirng = funciton(){
return this.name;
};
};
function B(){
this.name = 'B';
};
//我们想直接通过实例化B输出B的name,但是在这里B并没有toString(),所以,我们通过继承实现它
B.prototype = new A(); //通过B.prototype继承A的属性;
B.prototype.constructor = B;//这一步很重要,因为我们在通prototye继承A的时候,发生了副作用(改变了B的构造函数)。
var b = new B();
b.toString();//'B'
例2.1
//直接引用prototype实现继承
function A(){
this.name = 'shape';
}
A.prototype.toString = function() {
return this.name;
};
function B() {
this.name = 'B';
}
B.prototype = A.prototype;
B.prototype.constructor = B;
var b = new B();
b.toString();//'B'
// 但是!此例子会出现比较严重的问题,即当在子对象添加prototype.write()时,父对象也会有write()
B.prototype.write = function(){
console.log('This is B.');
};
var a = new A();
a.write();//This is B.
//这是因为,在这次的继承中,B.prototype与A.prototype指向同一内存空间。
下面我们通过例2.2实现子对象继承父对象且两者互不干扰
例2.2(临时构造符new F())
function A(){
this.name = 'shape';
}
A.prototype.toString = function() {
return this.name;
};
function B() {
this.name = 'B';
}
var F = function(){};
B.prototype = new F();
F.prototype = A.prototype;
B.prototype.constructor = B;
var b = new B();
b.toString();//'B'
B.prototype.write = function(){
console.log('This is B.');
};
var a = new A();
a.write();//Uncaught TypeError: a.write is not a function
若想了解更多,可查看书籍
《javascript面向对象编程指南(第二版)》
or
《Object-Oriented JavaScript(Third Edition)》