1.class概述
2.class的getter和setter
3.class静态方法和静态属性
4.new.target属性
<script>
//es5封装一个对象
//缺点:不利于语言和语言之间的转化(java,c++)
//创建一个构造函数
function Person(name,age){
this.name = name;
this.age = age;
}
//将方法定义再原型中,提高性能
Person.prototype.run = function(){
console.log(this.name + "is runing");
}
let p = new Person("nike"); // nike is runing
p.run();
console.log(p);//查看结构
//es6类的定义
class Person{
//构造方法
constructor(name,age){
this.name = name;
this.age = age;
}
//普通方法
//新的语法,函数的定义一定要用简写的方式,必须省略function
//写在class中的方法,是定义在类的原型中的
run(){
console.log(this.name + "is runing");
}
}
//实例化跟es5一样
let p = new Person("mink",300)
p.run();
console.log(p);//查看结构 _proto__:// constructor: class Person
//总结:1.class中的方法都是定义在原型中的 2.class的方法必须简写,不能带function
// 3.class中的构造函数用constructor来定义 4.class类的方法,不能直接调用,一定要使用new关键字来进行实例化对象
//**********************************************************************************//
//2.class中的getter和setter
class Animal{
set prop(name){
this.name = name;
}
get prop(){
return this.name;
}
set age(value){
if(value<12){
this.test = value;
}else{
this.test = 0;
}
}
get age(){
return this.test;
}
}
//当我们没有写constructor方法的时候,系统会提供一个默认的空参数,没有代码的constructor方法
let ani = new Animal();
ani.prop = "tiger";
console.log(ani.prop); //tiger
ani.age = 19;
console.log(ani.age); //0
//**********************************************************************************////
//3.静态方法和静态属性
function Preson(){}
Preson.eat = function(){
console.log("eating")
}
Preson.eat();
//class
class Animal {
constructor(color) {
this.color = color;
}
static run() {
console.log(this); //静态方法中的this指向类
console.log("running");
console.log(this.color);
}
}
let rabbit = new Animal("white"); //undefined
//给class添加静态属性
Animal.color = "black";
Animal.run();
</script>