JavaScript面向对象继承方法
1.原型链
function superType()
{
this.color = "black";
}
superType.prototype.saycolor = function()
{
document.write(this.color);
}
function subType()
{
this.name = "jack";
}
subType.prototype = new superType();
subType.prototype.sayname = function()
{
document.write(this.name);
}
var a = new subType();
a.sayname();
a.saycolor();
就是相当于subType的原型是superType的一个实例,superType的实例属性位于subType的原型中,subType的原型作为一个实例可以调用superType的原型的方法,
a→subType.prototype→superType.prototype(→Object.prototype→null)
借用构造函数
function superType()
{
this.color = "black";
this.saycolor =function()
{
document.write(this.color);
}
}
function subType()
{
superType.call(this)
}
var a = new subType();
a.saycolor();
ps,因为仅仅是借用构造函数,所以无法函数复用
组合继承
一半儿是原型链,一半儿是借用构造函数
function superType()
{
this.color = "black";
}
superType.prototype.saycolor = function()
{
document.write(this.color);
}
function subType()
{
superType.call(this)
}
subType.prototype = new superType();
subType.prototype.constructor = subType;
var a = new subType();
a.saycolor();
最常用的一种继承模式
原型式继承和寄生式继承
原型式继承
var person = {
name : "Jason",
age : 19,
}
var a = Object.create(person)
a.name="jack";
a.age=188;
document.write(a.name);
document.write(a.age);
var b = Object.create(a)
b.name="john";
b.age=23223;
document.write(b.name);
document.write(b.age);
没必要创建构造函数的时候
寄生式继承
var person = {
name : "Jason",
age : 19,
}
function newone(o)
{
var clone = Object(o);
o.sayHi = function(){
alert("hi");
}
return clone;
}
var a = newone(person);
a.sayHi();
寄生组合式继承
function superType()
{
this.color = "black";
}
superType.prototype.saycolor = function()
{
document.write(this.color);
}
function subType()
{
superType.call(this)
}
function f(subType,superType)
{
var a = Object(superType.prototype);
a.constructor = subType;
subType.prototype = a;
}
f(subType,superType);
subType.prototype.constructor = subType;
var a = new subType();
a.saycolor();