JavaScript中的继承

[b][color=red]1、对象冒充[/color][/b]

先创建一个Person类:
function Person(name, age){
this.name = name
this.age = age
this.sayHello = function(){
alert("Hello, I'm " + this.name + ".")
}
}

接着要创建一个Employee类,这个类有Person所拥有的name和age属性,另外还有自己的salary属性和showMeTheMoney()方法,可以这么做:
function Employee(name, age, salary){
this.newMethod = Person
this.newMethod(name, age)
delete this.newMethod
this.salary = salary
this.showMeTheMoney = function(){
alert(this.name + "$" + this.salary)
}
}

上面代码看起来有些复杂,其实它只是把Person当作单纯的函数,在Employee构造的时候调用一遍罢了。这个newMethod只用于构造对象,构造完毕后就没有用处,所以用完之后可以用delete操作符将其删除。

[b][color=red]2、call()方法[/color][/b]
每个function对象都有一个call()方法,它的第一个参数是用作this的对象,其它参数都直接传递给函数自身。例如:
function say(word){
alert(word + ", I'm " + this.name)
}

var yuan = new Object
yuan.name = "yuan"
say.call(yuan, "Hello") //alert: Hello, I'm yuan

利用call方法,可以简化前面的Employee代码:
function Employee(name, age, salary){
//this.newMethod = Person
//this.newMethod(name, age)
//delete this.newMethod
Person.call(this, name, age)//前面三行代码用这一行代替了
this.salary = salary
this.showMeTheMoney = function(){
alert(this.name + "$" + this.salary)
}
}


[b][color=red]3、apply()方法[/color][/b]
和call()方法一样,每个function对象都有一个apply()方法,它的第1个参数和call()方法一样,第2个参数是一个数组,这个数组是要传给function的参数的数组。用apply()改写上面的代码:
function Employee(name, age, salary){
//Person.call(this, name, age)
Person.apply(this, [name, age])
this.salary = salary
this.showMeTheMoney = function(){
alert(this.name + "$" + this.salary)
}
}


[b][color=red]4、原型链[/color][/b]
function对象的prototype属性是个模板,要实例化的对象都以这个模板为基础。(详见[url="http://yuan.iteye.com/blog/370861"]这里[/url])总之,prototype的任何属性和方法(方法也是一种属性)都被传递给那个“类”的所有实例。那我们就可以给某个function的prototype直接赋值为某个对象,这样的话,这个被赋值的对象的所有属性和方法都将被传递给这个function构造出来的实例,可以利用这一点实现继承机制。[url="http://yuan.iteye.com/blog/370861"]之前[/url]说过:属性由构造函数定义,方法由原型(prototype)定义,所以可以将上面的代码再次修改如下:
//定义Person类
function Person(name, age){
this.name = name
this.age = age
}

Person.prototype.sayHello = function(){
alert("Hello, I'm " + this.name + ".")
}

//定义Employee类
function Employee(name, age, salary){
//Person.call(this, name, age)
Person.apply(this, [name, age])
this.salary = salary
}

Employee.prototype = new Person
Employee.prototype.showMeTheMoney = function(){
alert(this.name + "$" + this.salary)
}

这里,new Person创建了一个Person对象,它有Person对象的所有属性和方法,把它赋值给Employee的prototype意味着Employee构造出来的所有实例都将拥有Person的属性和方法。这样便实现了继承。
在原型链中,instanceof运算符的运行方式很独特。对Employee的所有实例,instanceof为Employee和Person都返回true。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值