1. 对象冒充
实例:
var Parent = function (username) {
this.username = username
this.getUserName = function () {
console.log('username:' + username)
}
}
var Child = function (username, age) {
this.method = Parent
this.method(username)
delete this.method
this.getAge = function () {
console.log('age:' + age)
}
}
var p = new Parent('Tim')
var s = new Child('Little Time', 5)
p.getUserName()
s.getUserName()
s.getAge()
2. call方式
call方法是Function类中的方法
call方法的第一个参数的值赋值给类(即方法)中出现的this
call方法的第二个参数开始依次赋值给类(即方法)所接受的参数
实例:
var Parent = function (username) {
this.username = username
this.read = function () {
console.log('read your ' + username)
}
}
var Child = function (username, age) {
Parent.call(this, username)
this.age = age
this.getAge = function () {
console.log('appear your age :' + age)
}
}
var p = new Parent('Tom')
var s = new Child('little tom', 12)
p.read()
s.read()
s.getAge()
3. apply方式
apply方法接受2个参数,
第一个参数与call方法的第一个参数一样,即赋值给类(即方法)中出现的this
第二个参数为数组类型,这个数组中的每个元素依次赋值给类(即方法)所接受的参数
实例:
var Parent = function (username) {
this.username = username
this.getName = function () {
console.log('username:' + username)
}
}
var Child = function (username, age) {
Parent.apply(this, new Array(username))
this.age = age
this.getAge = function () {
console.log('age:' + age)
}
}
var p = new Parent('Shary')
var s = new Child('little shary', 19)
p.getName()
s.getName()
s.getAge()
4. 原型链方式
即子类通过prototype将所有在父类中通过prototype追加的属性和方法都追加到Child,从而实现了继承
实例:
var Parent = function () {}
Parent.prototype.username = 'parent'
Parent.prototype.getName = function () {
console.log('username:' + this.username)
}
var Child = function () {}
Child.prototype = new Parent()
Child.prototype.getAge = function (age) {
console.log('age:' + age)
}
var p = new Parent()
p.getName()
var s = new Child()
s.getName()
s.getAge(70)