JS封装,对象继承

1,函数封装

function Cat(name, color) {
//构造器的属性是每个实例独有的
    this.name = name;
    //通过this把属性,和实例对象绑定
    this.color = color;
}
Cat.prototype.type = "动物";
//构造器的prototype是所有实例公用的
Cat.prototype.eat = function() {
    alert("吃老鼠");
}
var cat1 = new Cat("kitty", "white");
cat1.eat();



2,构造函数的继承

    a,在构造函数内绑定

<span style="font-size:14px;">function Animal() {
    this.spieces = "动物";
}
function Cat(name, color) {
    Animal.call(this, spieces);
    //Animal函数调用了call方法,this指向Cat,speices是传入Animal的参数
    //相当于Cat.speices = "动物";
    this.name = name;
    this.color = color;
}
var cat1= new Cat("momo", "yellow");
alert(cat1.spieces);</span>

    b,prototype模式

如果猫的prototype对象指向Animal的实例,那么猫的所有实例都继承Animal

<span style="font-size:14px;">function Animal() {
    this.species = "动物";
}

function Cat(name, color) {
    this.name = name;
    this.color = color;
}
Cat.prototype = new Animal();
//把Cat的prototype指向Animal的实例,那么Cat的所有实例都继承Animal
Cat.prototype.constructor = Cat;
var cat1 = new Cat("momo", "white");
alert(cat1.species);</span>
c,把固定的属性写在Animal的prototype里,让Cat直接继承Animal的prototype(不过要个空对象作为中介,不然Cat.prototype.constructor = Cat的时候,会把Animal的constructor也换了)

function Animal() {
}
Animal.prototype.species = "动物";
//把species属性固定在prototype中

function Cat(name, color) {
    this.name = name;
    this.color = color;
}

function extend(Child, Parent) {
  var F = function(){};
  F.prototype = Parent.prototype;
    //用空对象作为中介
  Child.prototype = new F();
  Child.prototype.constructor = Child;
}
extend(Cat, Animal);
//跳过Animal直接继承Animal的prototype
var cat1 = new Cat("momo", "white");
alert(cat1.species);

d,通过for-in循环赋值

function Animal() {
}
Animal.prototype.species = "动物";

function Cat(name, color) {
    this.name = name;
    this.color = color;
}

function extend2(Child, Parent) {
    var p = Parent.prototype;
    var c = Child.prototype;
    for(var i in p) {
        <span style="color:#ff0000;">//每次循环,获得p里的属性名</span>
        c[i] = p[i];
        //通过属性名,获得Parent的prototype值
    }
}
extend2(Cat, Animal);
var cat1 = new Cat("momo", "white");
alert(cat1.species);

2 ,可以通过重写来覆盖继承的属性
// 这样Animal的属性或方法就会被覆盖
Cat.prototype.species = "我是猫王";
console.log(cat1.species);







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值