2016-09-18 43 views
1

請看:
https://jsfiddle.net/2aLht10r/1/ enter image description here的JavaScript爲什麼「這個」不綁定在這個小提琴正確

你可以看到,我得到undefined時,我要的是得到B。 出於某種原因,第11行中的這個值是undefined,它應該是第17行中創建的a對象的這個值(在類B內)。

我的代碼有什麼問題?

這裏是小提琴代碼:

class A { 
    selector; 
    ui = { 
    selector: `${this.selector} aaa` 
    } 

    constructor(selector) { 
    this.selector = selector; 
    } 

    clog = console.log.bind(null, this.ui.selector) 
} 

class B { 
    selector; 
    ui = { 
    a: new A('B') 
    } 

    print = this.ui.a.clog.bind(this.ui.a); 
} 

new B().print(); 
+1

我看不出有任何代碼。只是一個截圖和一個鏈接。 – Clive

+0

有一個小提琴 – vlio20

+4

令人驚訝的是,有3k代表的人不知道這一點,但確定...如果你的代碼不是文字,也可能是不可見的。 – Clive

回答

1

操作的排序絆倒你。

class A { 
    selector; 
    ui = { 
    selector: `${this.selector} aaa` 
    } 

    constructor(selector) { 
    this.selector = selector; 
    } 
} 
console.log(new A("thing").ui.selector) 

打印undefined aaa就像你說的,因爲它是相同的:

class A { 
    constructor(selector) { 
    this.ui = { 
     selector: `${this.selector} aaa` 
    }; 

    this.selector = selector; 
    } 
} 
console.log(new A("thing").ui.selector); 

所以你ui屬性存儲this.selector + 'aaa'已分配傳遞到構造函數的值之前。

也許你會更好,這樣做:

class A { 
    ui = { 
    selector: null, 
    }; 

    constructor(selector) { 
    this.ui.selector = `${selector} aaa`; 
    } 
} 
console.log(new A("thing").ui.selector) 
+0

感謝您指出錯誤。你能否建議其他一種方法來使用通過構造函數傳遞的值,然後再使用它(在阻塞函數中)? – vlio20

+0

增加了另一個片段。實際上,我不清楚你爲什麼在這裏使用課堂。至少在給出你的例子時,你可能會更好地使用一個正常的函數來返回一個對象。 – loganfsmyth

+0

這裏是一個工作小提琴:https://jsfiddle.net/2aLht10r/2/ – vlio20