javascript原型链

这是前天看到的一片文章,因为一些原因昨天没有保存下来,今天重新进行整理。

一.js的封装

 1.最简单的对象封装

var cat1={};
cat1.name='黑猫';
cat1.sex='公';
 2.使用函数封装

function animal(){
  return {
    name:'黑猫',
    sex:'公'
  }
};
var cat1=animal();
 3.构造函数

function Animal(){
    this.name='黑猫';
    this.sex='公';
}
cat1=new Animal();
 4.原型链prototype

function Animal(){
  this.name='黑猫';
  this.sex='公';
}
Animal.prototype.property='猫';
var cat1=new Animal();
 5.检测原型链

alert(Animal.prototype.isPrototypeOf(cat1))
//true;
alert(cat1.hasOwnProperty('name'));
//ture;
alert(cat1.hasOwnProperty('property'));
//false
alert('name' in cat1);
//true;
alert('property' in cat1);
//true

二.构造函数的继承

 1.apply,call继承

function Animal(){
  this.property='猫';
}
function Cat(){
  this.name='黑猫';
  this.sex='公';
}
function Cat(){
  Animal.apply(this,arguments);
  this.name='黑猫';
  this.sex='公';
}
 2.prototype

Cat.prototype=new Animal();
Cat.prototype.constructor=Cat;
 3.直接继承prototype

Cat.prototype=Animal.prototype;
Cat.prototype.consturctor=Cat;
 4.利用空对象作为中介
function F(){};
F.prototype=Animal.prototype;
Cat.prototype=new F();
Cat.prototype.constructor=Cat;
function extend(child,parent){
  function F(){};
  F.prototype=parent.prototyep;
  child.prototype=new F();
  child.prototype=child;
  child.uber=parent.prototype;
}
 5.拷贝继承

function Animal(){};
Animal.prototype.property='猫';
function extend1(child,parent){
  var p=parent.prototype;
  var c=child.prototype;
  for(var i in p){
    c[i]=p[i];
  }
  c.uber=p;
}

三.非构造函数的继承

 1.object()方法;

function object(o){
  function F(){};
  F.prototype=o;
  return new F();
};
cat1=object(cat2);
cat1.name='白猫'
 2.浅拷贝

function extendCopy(p){
  var c={};
  for(var i in p){
    c[i]=p[i];
  }
  c.uber=p;
  return c;
};
var Doctor=extendCopy(Chinese);
Doctor.career='医生';
alert(Doctor.nation);
//中国
 3.深拷贝

function extendCopy1(p,c){
  var c=c||{};
  for(var i in p){
    if(typeof p[i]===='object'){
      c[i]=(p[i].constructor===Array)?[]:{};
      extendCopy1(p[i],c[i]);
    }else{
      c[i]=p[i];
    }
  }
  return c;
}













  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值