总结先:
class的一般方法定义在类的原型上,实例会继承原型上的所有方法;
class的静态属性和静态方法定义在类上,实例不会继承静态属性和静态方法。访问静态属性或调用静态方法,均通过类名调用。
举个例子:
class Point{
static staticX = 1;
static staticY = 1;
constructor(x,y){
this.x = x;
this.y = y;
}
toString(){
return this.x + "," + this.y;
}
static toValue(p){
return p.x+p.y;
}
}
let p = new Point(1,2);
let s = p.toString(); //返回"1,2"
let val = Point.toValue(p);//返回3
console.log(Point.staticX,Point.staticY); //输出1 1
console.log(Object.getOwnPropertyNames(Point.prototype));//输出 ["constructor", "toString"]
console.log(Object.getOwnPropertyNames(p)); //输出["x", "y"]
console.log(Object.getOwnPropertyNames(Point));//输出["length", "prototype", "toValue", "name", "staticX", "staticY"]
如果没有static修饰呢?
class Point{
x;
y;
toString(){
return this.x + "," + this.y;
}
toValue(){
return this.x+ this.y;
}
}
const p = new Point();
p.x = 1;
p.y = 2;
console.log(Object.getOwnPropertyDescriptors(Point.prototype));
console.log(Object.getOwnPropertyDescriptors(p));
哦,没有static修饰,就是实例的属性了。
所以,上面也可以这样写:
class Point{
x;
y;
constructor(x,y){
this.x = x;
this.y = y;
}
toString(){
return this.x + "," + this.y;
}
toValue(){
return this.x+ this.y;
}
}
const p = new Point(1,2);
这样是不是更像面向对象编程中类的写法:x,y是属性,constructor是构造函数,toString和toValue是方法。
注意哈,与webpack、react搭配使用时,解析class需要安装插件@babel/plugin-proposal-class-properties
//weppack.config.js
const path = require('path');
const HtmlWebapckPlugin = require("html-webpack-plugin");
const {CleanWebpackPlugin} = require("clean-webpack-plugin");
module.exports = {
mode:'development',
// devtool:'cheap-source-map',
// mode:'production',
devServer:{
port:3000,
contentBase:path.join(__dirname,'dist')
},
entry:{
'index':"./src/index.js"
},
output:{
filename:"[name].bundle.js",
path:path.join(__dirname,"dist"),
chunkFilename:"[name].bundle.js"
},
module:{
rules:[
{
test:/\.js$/,
include:/src/,
exclude:/node_modules/,
use:{
loader:'babel-loader',
options:{
// presets:['@babel/preset-react']
presets:[
[
'@babel/preset-env',{
modules:false
}
]
],
plugins:['@babel/plugin-proposal-class-properties']
}
}
},
{
test:/\.css$/,
include:/src/,
use:['style-loader','css-loader'],
}
]
},
plugins:[
new HtmlWebapckPlugin({
template:'./index.html'
}),
new CleanWebpackPlugin()
]
}