Es5之前
function Person(name,age) {
this.name = name;
this.age = age;
}
/*start*/
Person.prototype.showName = function () {
return `名字为${this.name}`;
};
Person.prototype.showAge = function () {
return `年龄为${this.age}`;
}
/*end*/
/*start*/
/* Object.assign(Person.portotype,{
showName(){
return `名字为${this.name}`;
},
showAge(){
return `年龄为${this.age}`;
}
}); */
/*end*/
let p1 = new Person('Hansnen',18);
console.log(p1.showName());
console.log(p1.showAge());
Es6变形后
class Person{
constructor(name,age){//构造方法(函数),调用new,自动执行
//console.log(`构造函数执行了,${name},${age}`);
this.name = name;
this.age = age;
}
showName(){
return `名字为${this.name}`;
}
showAge(){
return `年龄为${this.age}`;
}
}
let p1 = new Person('Hansen',18);
console.log(p1.showName()+'--'+p1.showAge());
es6中的 变量名动态函数名
let aa = "method";
let bb = "Test";
let Person = class {
constructor(name,age){
this.name = name;
this.age = age;
}
[aa+bb]() {
console.log( `名字为:${this.name}`);
}
[aa]() {
console.log( `名字为:${this.name}`);
}
}
let person = new Person("kirin",18)
person[aa] === person.method && console.log("true");
person[aa+bb] === person.methodTest && console.log("true");
console.log([aa+bb]) //输出结果为:数组:["methodTest"
1.ES6是没有提升功能的,再ES5,用函数模拟是可以的,默认函数提升.
class Person{
constructor(){
this.name ="aa";
}
}
var p1= new Person();
console.log(p1); // Person {name: "aa"}
如果先实例化,就会报错
var p1= new Person();
console.log(p1); //报错 ‘ Person is not defined’ es6是没有提升功能的
class Person{
constructor(){
this.name ="aa";
}
}
- es6中的this
改变this
1.fn.call(this指向谁,args1,args2…)
2.fn.apply(this指向谁,[args1,args2]);
3.fn.bind() - class里面取值函数(getter),存值函数(setter)
class Person{
get aaa(){
return 'aaa的属性';
}
set aaa(val){
console.log(`设置aaa属性,值为:${val}`);//这里为设置属性
}
}
let p1 = new Person();
p1.aaa = '1223';
console.log(p1.aaa);//用get去获取属性
- 静态方法 类身上的方法
class Person{
showName(){
return '这是showName方法';
}
static aaa(){
return '这是静态方法';
}
}
let p1 = new Person();
console.log(p1.showName());
console.log(Person.aaa());
继承
es5
function Person(name){
this.name = name;
}
Person.prototype.showName =function(){
return `名字是 ${this.name}`
}
function Student(name){
//Person.call(this,name)
this.name = name;
}
Student.prototype = new Person(); //通过原型链来实现继承,利用原型让一个引用类型继承另一个引用类型的属性和方法
var stu1 = new Student('sss')
console.log(stu1.showName()); //名字是 sss
es6 extends
class Person{ //父类
constructor(name){
this.name = name;
}
showName(){
return `名字是 ${this.name}`
}
}
class Student extends Person{ //子类实现继承
}
var stu1 = new Student('sss')
console.log(stu1.showName()); //名字是 sss
class Person{
constructor(name){
this.name = name;
}
showName(){
console.log('父类的showName');
}
}
class Student extends Person{
/*如果直接是constructor(),就会覆盖父类的构造函数,会报错,所以要在参数中加上父类构造函数中有的参数,然后加上子类特有的参数,然后super()调用下,super里面参数为父类的*/
constructor(name,skill){
super(name); //调用父类的
this.skill = skill;
}
showName(){
super.showName(); //super让父级的方法先执行
console.log('子类的showName') //如果没有调用父类的showName 此时子类会把父类的showName覆盖
}
}
var stu1 = new Student('sss','技能')
console.log(stu1.showName());