- 1.静态属性:当想给所有对象属性时,可以设置属性为静态属性,减少实例化对象体积
- 2.静态方法(单例模式)
- 3.访问器
class Gz {
static address = "gaoxinsilu";
constructor(name, age) {
this._name = name;
this.age = age;
}
set name(name) {
this._name = name;
}
get name() {
return this._name;
}
static create(...args) {
return new this(...args);
}
say(msg) {
return this._name + this.age +
"的地址是:" + Gz.address + ":" + msg
}
}
let gz = new Gz("gz", 12);
gz.name = "kxf";
console.log(gz.name);
// console.log(gz);
// console.log(gz.say("xixi"));
// console.log(Gz.create("gz", 12));
let data = [
{ name: "SQL", price: 121 },
{ name: "CSS", price: 111 },
{ name: "HTML", price: 101 }
];
class Base {
constructor(data) {
this.modelData = data;
}
get price() {
return this.modelData.price;
}
static create(data) {
return data.map((item) => new Base(item));
}
static maxPrice(data) {
return data.sort((a, b) => {
return b.price - a.price;
})[0].price;
}
static totalPrice(data) {
return data.reduce((pre, cur) => {
return pre + cur.price;
}, 0);
}
}
let gz = Base.create(data);
console.log(Base.maxPrice(gz));
console.log(Base.totalPrice(gz));
方法的重写
let data = [
{ name: "SQL", price: 121 },
{ name: "CSS", price: 111 },
{ name: "HTML", price: 101 }
];
class Base {
constructor(data) {
this._data = data;
}
show() {
return "Base show";
}
}
class Search extends Base {
constructor(data, locator) {
super(data);
this.locator = locator;
}
info() {
return {
a: super.show(),
locator: this.locator
};
}
show() {
// return super.show();
return "@#$234";
}
}
let search = new Search([], "#box");
console.log(search.show());
- 4.使用Symbol属性保护;私有属性private
class Gz {
#url = "http://www.w3.org/"
static address = "陕西省"
constructor(name, age) {
this.name = name;
this.age = age;
this[protecteds] = {}
this[protecteds].cname = "haha"
}
static create(...args) {
return new this(...args);
}
set cname(value) {
this[protecteds].cname = value
}
get cname() {
return this[protecteds].cname
}
get address() {
return Gz.address
}
get url() {
return this.#url
}
showInfo() {
return this.name + ":" + this.age;
}
}
let gz = Gz.create()
console.log(gz)
class User {
constructor() { }
show() {
return this.name
}
}
class Person extends User {
constructor(name) {
super()
this.name = name
}
}
let pp = new Person("gz")
console.log(pp)```