es5環(huán)境下寫構(gòu)造函數(shù)
//創(chuàng)建構(gòu)造函數(shù)
function Person(name){
//定義屬性
this.name = name
}
//定義方法
Person.prototype.showName = function(){
return `my name is ${this.name}`
};
Person.prototype.showAge = function(age){
this.age = age;
return `my age is ${this.age}`
};
//創(chuàng)建一個實(shí)例
let p = new Person('bob','man');
//調(diào)用
console.log(p.sex);
console.log(p.showname());
console.log(p.showage(18));
繼承
function Children(name,boy){
//繼承父級屬性
Person.call(this,name);
//定義子級自己的屬性
this.boy = boy;
}
//繼承父級的方法
Children.prototype = new Person();
//定義子級自己的方法
Children.prototype.sayWord = function(){
return `i like ${this.boy}`;
};
//創(chuàng)建子級的實(shí)例
let c = new Children('cindy','girl','bob');
//打印父級繼承過來的屬性,調(diào)用父級繼承過來的方法
console.log(c.sex);
console.log(c.showname());
console.log(c.showage(16));
//調(diào)用子級自己的方法
console.log(c.sayword());
es6環(huán)境下的構(gòu)造函數(shù)
//創(chuàng)建構(gòu)造函數(shù)
class Father{
constructor(name,sex){
//定義屬性
this.name = name;
this.sex = sex;
}
//定義方法
showName(){
console.log('father fn showName is running');
return `my name is ${this.name}`;
}
showAge(age){
this.age = age;
return `my age is ${this.age}`;
}
}
//創(chuàng)建實(shí)例
let f = new Father('bob','man');
//打印屬性陷揪,調(diào)用方法
console.log(f.name);
console.log(f.showName());
console.log(f.showAge(18));
繼承
class Children extends Father{
constructor(name,sex,hobby){
//繼承屬性
super(name,sex);
//添加子級自己的屬性
this.hobby = 'sing'
}
//屬于子級自己的方法
showLike(data){
return `i like ${data}`
}
//定義與父級同名的方法會把父級的方法覆蓋
showName(){
//因此需要通過super去調(diào)用父級的方法瓢娜,但是父級方法里面的return拿不到
super.showName();
console.log('children fn showAge is running');
}
}
//創(chuàng)建子級的實(shí)例
let c = new Children('cindy','girl');
//從父級繼承的屬性和方法
console.log(c.name)
console.log(c.showAge(16));
//屬于子級自己的屬性和方法
console.log(c.showLike('bob'));
console.log(c.hobby);
//覆蓋了父級的方法
console.log(c.showName());
//返回結(jié)果
//father fn showName is running 父級函數(shù)被調(diào)用
//children fn showAge is running 子級自己的操作
//undefined 但是由于子級沒有return數(shù)據(jù)品姓,而且又無法獲取父級函數(shù)return的數(shù)據(jù)缕允,因此undefined
class的set和get
class Demo{
constructor(){
}
set name(val){
console.log('set name='+val)
}
get name(){
console.log('get name')
}
}
let d = new Demo();
d.name = 'lili';
console.log('-----------------我是分割線------------------')
let a = d.name;
//輸出結(jié)果
//set name=lili
//-----------------我是分割線------------------
//get name
clsss的靜態(tài)方法
class Demo{
constructor(){
this.name = 'bob';
this.age = 18;
}
showName(){
console.log(this.name)
}
static showAge(){
console.log('static')
}
}
let d = new Demo();
d.showName();
//返回結(jié)果
//bob
Demo.showName();
//返回結(jié)果
//Uncaught TypeError: Demo.showName is not a function
d.showAge();
//返回結(jié)果
//Uncaught TypeError: d.showAge is not a function
Demo.showAge();
//返回結(jié)果
//static