JavaScript 面向对象高级——继承模式
栏目: JavaScript · 发布时间: 6年前
内容简介:方式1: 原型链继承(1)流程: 1、定义父类型构造函数。
JavaScript 面向对象高级——继承模式
一、原型链继承
方式1: 原型链继承
(1)流程:
1、定义父类型构造函数。
2、给父类型的原型添加方法。
3、定义子类型的构造函数。
4、创建父类型的对象赋值给子类型的原型。
5、将子类型原型的构造属性设置为子类型。
6、给子类型原型添加方法。
7、创建子类型的对象: 可以调用父类型的方法。
(2)关键:
- 子类型的原型为父类型的一个实例对象
// 1.定义父类型构造函数
function Supper() {
this.supProp = 'Supper property'
}
// 2.给父类型的原型添加方法
Supper.prototype.showSupperProp = function () {
console.log(this.supProp)
}
// 3.定义子类型的构造函数
function Sub() {
this.subProp = 'Sub property'
}
// 4.子类型的原型为父类型的一个实例对象
Sub.prototype = new Supper()
// 5.将子类型原型的构造属性constructor指向子类型
Sub.prototype.constructor = Sub
// 6.给子类型原型添加方法
Sub.prototype.showSubProp = function () {
console.log(this.subProp)
}
// 7.创建子类型的对象,可以调用父类型的方法
var sub = new Sub()
sub.showSupperProp() // Supper property
sub.showSubProp() // Sub property
console.log(sub) // Sub
二、借用构造函数继承
方式2: 借用构造函数继承。
(1)流程:
1、定义父类型构造函数。
2、定义子类型构造函数。
3、在子类型构造函数中调用父类型构造。
// 1.定义父类型构造函数
function Person(name, age) {
this.name = name
this.age = age
}
// 2.定义子类型构造函数
function Student(name, age, price) {
// 3.在子类型构造函数中调用父类型构造
Person.call(this, name, age) // 相当于: this.Person(name, age)
/*this.name = name
this.age = age*/
this.price = price
}
var s = new Student('Tom', 20, 14000)
console.log(s.name, s.age, s.price) // Tom 20 14000
(2)关键:
- 在子类型构造函数中通过
call()调用父类型构造函数。
三、组合继承
方式3: 原型链+借用构造函数的组合继承。
1、利用原型链实现对父类型对象的方法继承。
2、利用 call() 借用父类型构造函数初始化相同属性。
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.setName = function (name) {
this.name = name
}
function Student(name, age, price) {
Person.call(this, name, age) // 为了得到属性
this.price = price
}
Student.prototype = new Person() // 为了能看到父类型的方法
Student.prototype.constructor = Student //修正constructor属性
Student.prototype.setPrice = function (price) {
this.price = price
}
var s = new Student('Tom', 24, 15000)
s.setName('Bob')
s.setPrice(16000)
console.log(s.name, s.age, s.price)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 028.Python面向对象继承(单继承,多继承,super,菱形继承)
- 面向对象:理解 Python 类的单继承与多继承
- Java继承(面向对象篇)
- 《JavaScript面向对象精要》之五:继承
- 码农上工06-Java面向对象-继承
- 组合还是继承,这是一个问题?——由模式谈面向对象的原则之多用组合、少用继承
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Master Switch
Tim Wu / Knopf / 2010-11-2 / USD 27.95
In this age of an open Internet, it is easy to forget that every American information industry, beginning with the telephone, has eventually been taken captive by some ruthless monopoly or cartel. Wit......一起来看看 《The Master Switch》 这本书的介绍吧!