{functionFather(name1){this.name1 = name1
}
Father.prototype.say1=function(){
console.log(`i am ${this.name1}`);}functionSon(name1, name2){
Father.call(this, name1)this.name2 = name2
}
Son.prototype = Father.prototype
Son.prototype.say2=function(){
console.log(`${this.name1}'s father is ${this.name1}`);}let son =newSon('bob','lucy')
son.say1()// i am bob
son.say2()// lucy's father is bob}
es6 的 class 面向对象
{classPerson2{constructor(name,age){this.name=name;this.age=age;}print(){
console.log('my name is '+this.name +', '+this.age +' years old.');}}let person=newPerson2('bob',20);
console.log(person);//Person {name: "bob", age: 20}
person.print();//my name is bob, 20 years old.}// 变量接受 class{let Person3 =class{constructor(name,age){this.name=name;this.age=age;}print(){
console.log('my name is '+this.name +', '+this.age +' years old.');}}let person=newPerson3('bob',20);
console.log(person);//Person {name: "bob", age: 20}
person.print();//my name is bob, 20 years old.}// 立即执行的 class{let Dog5 =newclass{constructor(json){this.name = json.name
this.age = json.age
this.hobbies = json.hobbies
}doSomething(something){
console.log(`${this.name}今年${this.age}岁了,爱好${this.hobbies},现在要去${something}`)}}({ name:'miss', age:20, hobbies:'主播'})
Dog5.doSomething('打游戏')// miss今年20岁了,爱好主播,现在要去打游戏}// getter setter 拦截{classDog6{constructor(propValue){this.propValue = propValue
}getprop(){
console.log('getter',this.propValue);returnthis.propValue
}setprop(val){
console.log('setter', val);this.propValue = val
}}let list =newDog6('hello')
list.prop ='world'// setter world
console.log(list.prop)// getter world / world}// static 静态方法和属性:不会继承,而是通过类直接调用{classDog7{static something ='hello'staticdo(){
console.log(Dog7.something)}}
Dog7.do()// hellolet dog =newDog7()
dog.do()// 报错}// 继承{classDog7{static something ='hello'staticdo(){
console.log(Dog7.something)}}classDog8extendsDog7{staticdo1(){
console.log('world')}}
Dog8.do()// hello
Dog8.do1()// world}//注意继承在 constructor 中使用 this,以及在子方法中调用父方法,需要使用 super{classDog5extendsDog4{constructor(json){// 只有调用了 super 后才可以使用 this 关键字,并对 Dog4 传入 jsonsuper(json)this.name = json.name
}interview(who){super.doSomething('玩耍')// doSomething() 是 Dog4 的方法,用 super 调用
console.log(`${this.name}的朋友是${who}`)}}}
es6 class 与es5的面向对象的区别:
写法不同,使用关键字 class
当 new 一个实例,默认有一个 constructor 方法,且默认返回实例对象(this),也可以返回另一对象