js继承 对象冒充和原型链继承

/*js中继承可以分为两种:对象冒充和原型链*/
一、对象冒充
//1. 临时属性方式
function Person (name) {
    this.name = name;
    this.say = function() {
        alert('My name is' + this.name);
    }
}

function F2E(name, id) {
    this.temp = Person;
    this.temp(name);
    delete this.temp;
    this.id = id;
    this.showId = function () {
        alert('My id is' + id);
    }

}

var simon = new F2E('simon', 9786);
simon.say();

simon.showId();


//2.call/apply方式,实质上是改变了this指针的指向
function Person (name) {
    this.name = name;
    this.say = function () {
        alert('My name is' + this.name);
    }
}

function F2E (name, id) {
    Person.call(this, name);
    this.id = id;
    this.showId = function () {
        alert('My id is' + this.id);
    }
}

var simon = new F2E('simon', 9867);
simon.say();
simon.showId();

二、原型链方式
function Person() {
    this.name = 'Simon';
}

Person.prototype.say = function () {
    alert('My name is ' + this.name);
}

function F2E(id) {
    this.id = id;
    this.showId = function() {
        alert('My id is' + this.id);
    }
}

F2E.prototype = new Person();

var simon = new F2E(9578);
simon.say();
simon.showId();
alert(simon.hasOwnProperty('id'));

<img id="theimg" src="http://files.jb51.net/file_images/article/201403/201434142223800.png?201424142242" alt="" />
                                                  原型链方式概念图

/*对象冒充的缺点:在OO概念中,new实例化后,对象就在堆内存中形成了自己的空间,值得注意的是,这个代码段。而成员方法就是存在这个代码段的,并且方法是共用的。
问题就在这里,通过对象冒充方式继承时,所有的成员方法都是指向this的,也就是说new之后,每个实例将都会拥有这个成员方法,并不是共用的,这就造成了大量的内存
浪费。并且通过对象冒充的方式,无法继承通过prototype方式定义的变量和方法,如以下代码将会出错*/
/*原型链的缺点:原型链方式继承,就是实例化子类时不能将参数传给父类,也就是为什么这个例子中function Person()没有参数,
而是直接写成了this.name=”Simon”的原因*/

//综合方法, 成员变量采用对象冒充方式,成员方法采用原型链方式

function Person (name) {
    this.name = name;
}

Person.prototype.say = function () {
    alert('My name is ' + this.name);
}

function F2E(name, id) {
    Person.call(this, name);
    this.id = id;
}

F2E.prototype = new Person();
//细节 showId 不能写在F2E.prototype = new Person(); 前面

F2E.prototype.showId = function () {
    alert('My id is ' + id);
}

var simon = new F2E('simon', 9576);
simon.say();
simon.showId();





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值