chrome 74;node 12 新增了 js 类私有域,包括私有变量,私有函数
class Mtest {
#privateField;
#privateMethod() {
console.log("call #privateMethod()")
return "[privateMethod " + this.#privateField + "]";
}
publicMethod() {
console.log("publicMethod this.#privateField", this.#privateField)
return this.#privateMethod();
}
static #privateStaticMethod() {
return "call privateStaticMethod";
}
static #PRIVATE_STATIC_FIELD;
// #constructor > Class constructor may not be a private method
constructor() {
console.log("Object.keys(this):",Object.keys(this),"私有属性不能用Object.keys") // []
this.#privateField = "privateField"
console.log(`privateField: this["#privateField"]:`, this["#privateField"])
console.log(`privateField: this.#privateField :`, this.#privateField)
}
static publicStaticMethod() {
Mtest.#PRIVATE_STATIC_FIELD = 42;
return Mtest.#PRIVATE_STATIC_FIELD;
}
static publicStaticMethod1() {
// 继承后 publicStaticMethod2 中的 this 指向子类 ; 故此不能用this
return Mtest.#privateStaticMethod();
}
static publicStaticMethod2() {
// 继承后 publicStaticMethod2 中的 this 指向子类 ; 故此不能用this
return this.#privateStaticMethod();
}
}
class SubClass extends Mtest {
#subPrivateField;
constructor() {
super();
// console.log(super.#privateMethod()) Unexpected private field
this.#subPrivateField = 23;
// this.#privateField > Private field "#privateField" must be declared in an enclosing class
}
}
let m = new Mtest()
m.publicMethod();
Object.getOwnPropertyDescriptors(m) // {}
console.log(Mtest.publicStaticMethod())
console.log(m)
let clone = {};
Object.assign(clone, m)
Object.setPrototypeOf(clone, Mtest.prototype)
try {
console.log(clone.publicMethod())
} catch (error) {
console.log(error.message)
console.log("Object.assign 不能克隆私有属性");
}
const m1 = structuredClone(m)
console.log("利用structuredClone m 到m1");
console.log("深度克隆不会克隆方法,克隆私有属性 m1.publicMethod == m.publicMethod :",m1.publicMethod == m.publicMethod)
// console.log(m1.publicMethod())
console.log(m1);
Object.setPrototypeOf(m1, Mtest.prototype)
console.log(SubClass.publicStaticMethod1()); // 42
// console.log(SubClass.publicStaticMethod2()); // 异常
console.log("SubClass publicMethod:",new SubClass().publicMethod())
打印输出:
Object.keys(this): [] 私有属性不能用Object.keys
privateField: this[“#privateField”]: undefined
privateField: this.#privateField : privateField
publicMethod this.#privateField privateField
call #privateMethod()
42
Mtest {}
Cannot read private member #privateField from an object whose class did not declare it
Object.assign 不能克隆私有属性
利用structuredClone m 到m1
深度克隆不会克隆方法,克隆私有属性 m1.publicMethod == m.publicMethod : false
{}
call privateStaticMethod
Object.keys(this): [] 私有属性不能用Object.keys
privateField: this[“#privateField”]: undefined
privateField: this.#privateField : privateField
publicMethod this.#privateField privateField
call #privateMethod()
SubClass publicMethod: [privateMethod privateField]