面向对象类

面向对象,类的实例、继承

类与实例

  1. 类的声明
function A(){
this.name = "name"
}
//es6
class A2{
   constructor(){
   	this.name="name"
   }
}
  1. 生成实例
new A(),new A2()

类的继承

  1. 如何继承
//借助构造函数继承
function P(){
	this.name = 'P'
}
P.prototype.say = function(){}//父类的原型对象无法被子类继承
function C(){
	P.call(this) //apply
	this.type = 'C'
}
//借助原型链继承
function P(){
	this.name = 'P'
	this.play = [1,2,3]
}
function C(){
	this.type = 'C'
}
C.prototype = new P()
var s1 = new C()
var s2 = new C()
s1.play.push(4)//s1与s2的play均改变,公用同一个对象
//组合方式
function P(){
	this.name = 'P'
	this.play = [1,2,3]
}
function C(){
	P.call(this)//拿到上下文
	this.type = 'C'
}
C.prototype = new P()
var s1 = new C()
var s2 = new C()
s1.play.push(4)//但是父类的构造函数执行了两次
//组合方式优化1
function P(){
	this.name = 'P'
	this.play = [1,2,3]
}
function C(){
	P.call(this)//拿到上下文
	this.type = 'C'
}
C.prototype = P.prototype
var s1 = new C()
var s2 = new C()
s1.play.push(4)//无法判断实例由父类创建的还是子类创建的
console.log(s2.constructor)
//组合方式优化2
function P(){
	this.name = 'P'
	this.play = [1,2,3]
}
function C(){
	P.call(this)//拿到上下文
	this.type = 'C'
}
C.prototype = Object.create(P.prototype)//原型对象就是参数
C.prototype.constructor = C//覆盖
var s1 = new C()
var s2 = new C()
s1.play.push(4)
console.log(s2.constructor)
  1. 继承方式
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值