Javascript学习笔记 What is "extend"

[size=large][b]1. 从关于“new”的一段代码开始[/b][/size]

从《JavaScript语言精粹》上看到一个关于“new”实现方法的猜测,实现正规,而且符合实际情况。下面把代码列下来。


Function.method('new', function(){
// 创建一个新对象,它继承自构造器函数的原型对象。
var that = Object.create(this.prototype);

// 调用构造器函数,绑定 -this- 到新对象上。
var other = this.apply(that, arguments);

// 如果它的返回值不是一个对象,就返回该新对象。
return (typeof other === 'object' && other) || other;
});


[size=large][b]2. 关于继承的实现[/b][/size]

假设上面写的正确,我们可以结合[url=http://baike.so.com/doc/477195.html]面向对象中继承[/url]的定义来实现JavaScript中的继承,即继承性是子类自动共享父类数据结构和方法的机制。

假设一个父类如下实现。

var Parent = function(x) {
this.x = x + 1;
};
Parent.prototype.getX = function() {
return this.x;
};


假设希望实现一个子类为Child。

子类则需要继承父类的属性和方法,根据原型链可以使用如下方法。

var Child = function() {
//此构造函数的实现下面会讨论
};
Child.prototype = new Parent();

依据上面new的实现,Child.prototype将会被挂载到Parent类(var Parent = function(){})原型链的下面。
那么所有Parent.prototype下所有的属性都会被Child.prototype使用(var that = Object.create(this.prototype);)。
那么就会有当有如两个实现的对象。
[code]
var p = new Parent();
var c = new Child();
[/code]
则,所有p的函数都会被c使用,这个情况符合继承的定义。

但是这种实现的问题是Parent的构造函数无法被继承,那么可以用如下代码实现。
[code]
var Child = function(x, y){
//$1:下面三行实现如Java中的this.parent()方法
this.method = Parent;
this.method(x);
delete this.method;

//Child自己的构造方法中的内容。
this.y = y;
};
[/code]
总体思路是通过改变Parent中this(即函数运行环境)来实现类似于其他语言中this.parent的方法。因为就构造函数而言,父类对于子类的影响体现为构造函数所改变this下的属性和方法。
因此$1的实现方式还可以替换为以下两种方法。
[code]
Parent.call(this, x);
//或
Parent.apply(this, new Array(x));
[/code]

总结以上,Child的实现如下。
[code]
var Child = function(x, y) {
Parent.call(this, x);

this.y = y;
};
Child.prototype = new Parent();
Child.prototype.getY = function() {
return this.y;
}
[/code]

[size=large][b]3. Child和Parent的原型链[/b][/size]

可以得到如下的原型链。[img]http://dl2.iteye.com/upload/attachment/0092/4006/ee43a05b-8348-3c5c-a0c1-befadf674369.png[/img]

[size=large][b]4. instanceof与typeof[/b][/size]
[code]
console.log(Child.prototype.constructor === Parent); //true
console.log(typeof Parent == "function"); //true
console.log(typeof Child == "function"); //true
[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值