类没有变量提升,所以需要放到代码的最前面
类里面的公用方法一定要加this
**创建class实例, **
class Star {
// 类的公用属性放到constructor函数里面
constructor(name,a,b){
this.name = name
this.a = a
this.b = b
this.num = a+b
}
age(){
console.log(this.a + this.b)
}
}
var isa = new Star('刘德华')
var isb = new Star('周润发',6,8)
var isNum = new Star('null',100,600)
isb.age()
console.log(isa.name,isb.name,isNum.num)
extends继承
// 继承父类 extends关键字
class Child extends Star{
}
// 这样就继承的父类的属性和方法
var child = new Child('张小三',10,20)
child.age='age:88'
console.log(child)
super子类向父类里面传递参数
// super 关键字
class Child extends Star{
constructor(name,a,b){
// 子类向父类里面传递参数
super(name,a,b)
}
super.age() //这样调用的是父类
}
var child = new Child('娃哈哈',250,30)
child.age()
子类调用父类的方法
class Star {
constructor(){
}
age(){
return '父类'
}
};
class Child extends Star{
constructor(){
}
age(){
console.log( super.age() + '子类')
}
}
var child = new Child()
child.age()
子类继承父类方法
class User{
constructor(x,y){
this.x = x
this.y = y
}
add(){
return this.x + this.y
}
}
class Child extends User{
constructor(a,b){
super(a,b)
this.a = a
this.b = b
}
ad(){
return this.a - this.b
}
}
var child = new Child(10,20);
console.log(child.ad())
构造函数
function info(name,age){
this.name = name
this.age = age
this.fun =function(){
return '哈哈哈'
}
}
var ldh = new info('刘德华',59)
var gdg = new Stat('郭德纲',49)
console.log(ldh.fun === gdg.fun) //false
//构造函数的实例成员只能通过实例化对象来访问 例如:
console.log(ldh.name)
//构造函数的静态成员只能通过构造函数本身来添加,也只能通过构造函数来访问 例如:
info.sex="男"
console.log(info.sex)
// 以上每一次创建实例都会开辟一个空间,这样会占用没必要的内存,解决方案:1
//构造函数的原型对象里面添加公用方法
Stat.prototype.fun = function () {
return '哈哈哈'
}
console.log(ldh.fun === gdg.fun) //true
//原理:每个对象都会有一个__proto__原型存在 , __proto__对象和原型对象的prototype是等价的
console.log(ldh.__proto__ === Stat.prototype) //true
方案2
function isfun() {
console.log(100000)
}
function Par(name, age) {
this.name = name
this.age = age
//这样指向的都是同一个函数,不会开辟重复的空间
this.fun =isfun
}
var pars = new Par(123, 666)
for (let i = 0; i < 10; i++) {
var par = new Par(3, 66)
par.fun(6)
// console.log(par.name)
}
console.log(pars.fun ===par.fun )
实例3
function Par(name, age) {
this.name = name
this.age = age
}
Par.prototype.fun = function(){
return this.name+this.age
}
var pars = new Par(123, 666)
pars.fun()
console.log(pars.fun())
原型constructor构造函数
function Info(name,age){
this.name = name
this.age = age
}
Info.constructor = {
a:{
name:'xxx'
},
b:{
age:'yyy'
}
}
// 给constructor赋值一个对象后则需要手动利用constructor指回原来的构造函数
Info.constructor={
constructor:Info
}
console.log(Info.constructor)