static 关键字
//定义静态变量
static RESOLVED = 'resolved';
// 静态方法(函数)
static isHuman(obj){
return obj instanceof person //对象与构造函数在原型链上是否有关系
}
<script>
// 基类、父类
class person{
constructor(name,age){
this.name = name;
this.age = age;
}
// 静态方法
static isHuman(obj){
// console.log("静态")
return obj instanceof person //对象与构造函数在原型链上是否有关系
}
// 方法
say(){
console.log("我会说话")
}
//没有逗号隔开
eat(){
console.log("我要吃饭")
}
}
// var p1 = new person('dj',20)
// p1.say()
//继承、扩展 Coder 为继承对象 son extends father
class Coder extends person{
constructor(name,age,salary){ //一定加参数
super(name,age);//在子类中手动调用父类 一定加参数
this.salary = salary;
}
say(){
console.log("一月3w")
}
walk(){
super.eat() //调用父类中的方法
}
}
var p2 = new Coder("zm",25,3000);
p2.eat()//我要吃饭 子类可以直接调用父类方法
p2.say()//一月3w 子类可以重写父类的方法
p2.walk() //我要吃饭
console.log( Coder.isHuman(p2))//true 父类上的静态方法子类也可以继承
console.log(p2)
</script>
子类 必须 在 constructor( )
调用 super( )
方法,否则新建实例时会报错。
子类是没有自己的 this
对象的,它只能继承自父类的 this
对象,然后对其进行加工,而super( )
就是将父类中的this对象继承给子类的。没有 super
,子类就得不到 this
对象
react
<script type="text/babel">
class Person{
constructor(name){
this.name = name;
this.mouth = '1z';
this.leg = '2t'
}
eat(){
console.log('我能吃饭')
}
say(){
console.log('i can say')
}
}
var p1 = new Person('du');
console.log(p1)//{name:"du", mouth: "1z", leg: "2t"}
//继承
class Man extends Person{
constructor(name,age){
super(name)//手动调用父类
this.name = name;
this.age = age;
}
}
var p2 = new Man('张三',100);
console.log(p2);//{mouth: "1z", leg: "2t", name: "张三", age: 100}
console.log(p2.leg)//2t
p2.eat()//我能吃饭
</script>
ES5中,JavaScript是没有继承的写法的,因此,通过使用 prototype
来达到目的。举个例子:
//构造函数People
function People (name,age){
this.name = name;
this.age = age
}
People.prototype.sayName = function(){
return '我的名字是:'+this.name;
}
//创建新的子类p1
let p1 = new People('harrisking',23); //People {name: "harrisking", age: 23}
p1.sayName();// '我的名字是xxx'
TS:
class Dog{
name:String;
age:Number;
constructor(name:string,age:number){
this.name = name;
this.age = age;
}
bark(){
alert('wwww')
}
}
let dog = new Dog('小白',10)
// dog.bark()
console.log(dog)