JavaScript继承、对象枚举-笔记

一、第一种继承(运用原型链)

Grand. prototype. LastName = "姓杨";
function Grand() {
}
var grand= new Grand();

Father. prototype= grand;
function Father() {
var Name= "也姓杨、";
document. write( Name);
}
var father= new Father();

Son. prototype= father;
function Son()
{
document. write( this. LastName);
}
var son= new Son();


输出结果:在son构造中,输出结果为:也姓杨、姓杨;

二、第二种继承(call,apply关键字)

function Human( name, sex, age){
this. name= name;
this. sex= sex;
this. age= age;
}
function HumanYang( name, sex, age, address){
Human. call( this, name, sex, age);
this. address= address;
document. write( name, sex, age, address);
}
var human= new HumanYang( "杨", "男", "20", "重庆");


输出结果:杨男20重庆

三、第三种继承(共有原型、多个构造函数共有一个原型)

father. prototype. lastName= "yang";
function father(){
}
function son(){

}
function herinert( Tagert, Object){
Tagert. prototype= Object. prototype;
}
herinert( son, father);
var son= new son();
document. write( son. lastName);


输出结果:yang;

herinert为封装继承的一个函数,放入函数可实现谁继承自谁;

第三种模式缺点:在子函数缘原型上加属性会改变父原型的值

四、第四种继承(圣杯模式)

father. prototype. lastName= "yang";
function father(){
}
function F(){}
f. prototype= father. prototype;
function Son(){
}
Son. prototype= f. prototype;


分析:所谓的圣杯模式就是用一个中间原型来连接两个函数;实质形成为原型链;这样在改动子元素的原型时不会为父原型加上任何属性;因为中间函数没有任何原型。

继承封装方法可以这样写:

function inherit( Target, Origin){
function F(){}
F. prototype= Target. prototype;
Origin. prototype= new F() //==Object.prototype=F.prototype
Target. prototype. constuctor= Tragt;
Target. prototype. uber= Origin. prototype;
}

封装继承的另外一种写法,来源于YUI3类库的一种写法;

var inherit=( function(){
var F= new function(){};
return function( Target, Origin){
F. prototype= Origin. prototype;
Target. prototype= new F();
Target. prototype. constuctor= Target;
Target. prototype. uber= Origin. prototype;
}
}());

你可能感兴趣的:(javaScript,javascript继承封装,圣杯模式,javascript继承)