我正在構建一個在游戲引擎和編輯器之間共享的類。我想在編輯器中定義一些屬性和方法,而不是引擎,所以我寫了以下代碼
class Asset{
constructor(){
this.prop1 = 1;
}
}
if (window.IS_EDITOR){
Asset.prototype.editorProp = 2;
}
class Room extends Asset{
constructor(){
super();
this.prop2 = 3;
console.log(this)
//expected: {prop1: 1, prop2: 3, editorProp: 2}
//what I get: {pro1: 1, prop2: 3}
}
}
我基本上只是想有條件地向建構式添加另一個屬性,但我很困惑為什么editorProp在我訪問this.
uj5u.com熱心網友回復:
我很困惑為什么
editorProp當我訪問this.
因為它在您物件的原型上,就像.constructor, 并且默認情況下不會列印console.log。如果您展開原型,或者您將console.log(Object.getPrototypeOf(this)). 您仍然可以像this.editorProp預期值一樣訪問它,因為它是繼承的。
我正在嘗試有條件地向建構式添加另一個屬性
如果要在建構式中將屬性添加到實體中,則實際上應該在建構式中進行:
class Asset {
constructor() {
this.prop1 = 1;
if (window.IS_EDITOR) {
this.editorProp = 2;
}
}
}
uj5u.com熱心網友回復:
就像指出的那樣,console.log只是記錄物件,而不是原型鏈中的內容。這樣做console.log(this.editorProp)確實會回傳2,因為現在使用了原型鏈。
如果你想看到原型變平的物件,使用in. 在下面的示例中,我添加了一個簡單的函式flat來執行此操作。
同樣值得注意的是,向類添加方法將使它們自動成為不可列舉的,但是如果向原型添加方法,它將是可列舉的。所以下面的一個例子我還添加了一個被呼叫的函式,fn但defineProperty用來阻止它是可列舉的。
window.IS_EDITOR = true;
class Asset{
constructor(){
this.prop1 = 1;
}
}
if (window.IS_EDITOR){
Asset.prototype.editorProp = 2;
//adding a function this will will be
//enumerable, so you might want to use
//defineProperty here.
Object.defineProperty(
Asset.prototype,
'fn',
{value: () => {console.log('fn called')}, enumerable: false});
}
class Room extends Asset{
constructor(){
super();
this.prop2 = 3;
console.log(this.flat());
this.fn();
//expected: {prop1: 1, prop2: 3, editorProp: 2}
//what I get: {pro1: 1, prop2: 3}
}
flat() {
const ret = {};
for (const i in this) ret[i] = this[i];
return ret;
}
}
new Room();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/400808.html
標籤:javascript 班级
