瞒天过海法处理父类构造函数带参数

这个方法以前从某个贴子上学的。但是只知道是那样用,不知道是为啥。我今天忽然明白了。以前一直奉行拿来主义,不求甚解( ̄▽ ̄)~* 。。太丢人了。。下面写一下我的理解,希望大家不要觉得我罗嗦


当父类的构造函数带参数时如何处理。我们先避开这个问题,看一下一个简单的类:

例1:
[code]
<SCRIPT LANGUAGE="JavaScript">
<!--
function MyClass(){
this.name = 'my defined class';
this.myMethod = myOuterMethod;
}

function myOuterMethod(){
alert(this.name); //这里的this, 即是MyClass的实例。这点很关键喔。
}

var mc = new MyClass();
mc.myMethod(); //打印 'my defined class'

//-->
</SCRIPT>

[/code]

类MyClass里定义了myMethod方法,它指向一个外部定义的函数(姑且这么叫)myOuterMethod。
当用MyClass的实例来调用这个myMethod方法时,可以发现myOuterMethod里的this其实就是MyClass的实例。

这个例子很好理解吧^_^。那么再看例2。。

例2:
[code]
<SCRIPT LANGUAGE="JavaScript">
function Parent(id){
this.id = id;
this.getLocation = function(){
alert(this.id + ' at XiaMen');
}
}

Parent.prototype.getId = function(){
alert(this.id);
}

function Child(id){
/**就像上面MyClass里的myMethod属性指向myOuterMethod方法那样。指向Parent函数*/
this._super = Parent;
/**执行这个方法.这个时候Parent函数 (注意它现在是函数)里的this为Child类的实例!*/
this._super(id);
}

Child.prototype = new Parent(); //继承

var c1 = new Child('katelin');
c1.getLocation(); // 打印 'katelin at XiaMen'
c1.getId(); // 打印 'katelin'
//-->
</SCRIPT>

[/code]

想让Parent里的属性变成自己的属性。例1的方法给了我们瞒天过海的启示~ 在Child类里令一个属性_super(随便取名的啦)指向父类的Parent方法。请对比下例1。这时_super就像myMethod, Parent就像myOuterMethod. 因此用Child的实例来调用_super方法时,Parent里面的this指的就是Child的实例~

因此我们执行this._super(id)的时候, Parent方法里的this.id, this.getLocation就这么变成了Child实例的囊中之物了∩__∩y 。但是, 相信大家已经看明白了,这仅限与写在Parent方法里的属性和方法喔(听着好怪)。


如果要继承写在Parent外面的方法,比如getId,那就得用Child.prototype = new Parent();这个就不说了。大家都知道得~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值