class语法
class Parent{
// new的时候,执行的构造函数【可写可不写;需要接受传递进来的实参信息,才需要甚至constructor】
constructor(x,y){
// this ->创建的实例
this.total = x + y;
}
num = 200; //等价于 this.num = 200 给实例在设置私有属性
getNum = ()=>{
// 箭头函数没有自己的this,所用到的this是宿主环境中的
console.log(this); //this->当前创建的实例
};
//================
sum(){
// 类似于 sum=function sum(){} 不是箭头函数
// 它是给Parent.prototype上设置公共的方法【sum函数是不可枚举的】
}
//================
// 把构造函数当做一个普通对象,为其设置静态的私有属性方法 使用时:Parent.xxx
static avg = 1000;
static average(){
}
}
Parent.prototype.y = 2000; //在外部手动给构造函数原生上设置公共的属性
let p = new Parent(10,20);
console.log(p);
继承的原理
/*基于extends 实现继承
1.首先基于call继承 React.Component.call(this) //this->Parent类的实例p
function Component(props,context,updater){
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
}
给创建的实例p设置四个私有属性:props/context/emptyObject/updater
2.在基于原型继承 Parent.prototype._proto_ === React.Component.prototype
实例 -> Parent.prototype -> React.Component.prototype -> object.prototype
实例除了具备Parent.prototype提供的方法之外,还具备了React.Component.prototype原型上提供的方法:isReactComponent、setState、forceUpdate
3.只要自己设置了constructor,则内部第一句话一定要执行super()
*/
class Parent 基于extends React.Component{
constructor(props){
// this -> p props->获取的属性
// super(); 等价于React.Component.call(this)
// this.props=undefined thhis.context=undefined this.refs={} ...
super(props)
// this.props=props this.context=undefined ...
}
x=100;
getX(){
}
}
let p = new Parent();
console.log(p);