2017-06-21 48 views
1

我相信這可以使用箭頭函數解決,但我不知道如何。我想在render函數裏面訪問this.props。我知道我可以通過它作爲一個論點,但寧可不要。這可能使用箭頭功能?如果是這樣,我需要改變什麼?我該如何更改此JavaScript使用箭頭功能才能訪問屬性

class View { 
    constructor(options) { 
    this.options = options; 
    } 
    render(el, props = {}) { 
    this.props = props; 
    el.innerHTML = this.options.render(el); 
    } 
} 

var Test = new View({ 
    render() { 
    return `${this.props.test}` 
    // 
    // Also, tried ${props.test} in my template literal 
    // 
    } 
}); 

Test.render(document.getElementById("main"), { 
    test:"123" 
}) 
+0

沒有,則使用箭頭功能,這正是*不*可能的。你正在尋找'this.options.render.call(this,el)'。 – Bergi

+0

相關:[箭頭函數與函數聲明/表達式:它們是否等價/可交換?](https://stackoverflow.com/q/34361379/218196) –

回答

3

箭頭函數允許您訪問外部閉包而不是調用函數空間。函數的一個定義點是將它與被調用者的變量隔離開來。箭頭函數只是使上下文或對象與其定義關閉相等。因此

var that = this; 
(() => console.log(that === this))(); 

將打印真實的,而

var that = this; 
(function(){console.log(that === this)})(); 

將打印假 使箭頭的函數可以訪問this方面的原因,是因爲它在那裏定義,而不是因爲它被稱爲那裏。

強制上下文對象的唯一方法是通過使用Function.prototype.callFunction.prototype.apply

+0

你搖滾! 'this.options.render.call(this,el)是有用的。 –

1

你需要的this.props = props分配?你可以有這樣的事情。

class View { 
 
    
 
    constructor(options) { 
 
    this.options = options; 
 
    } 
 

 
    render(el, props = {}) { 
 
    el.innerHTML = this.options.render(props); 
 
    } 
 
} 
 

 
var test = new View({ render: x => `${x.test}` }); 
 

 
test.render(document.getElementById("main"), { test:"123" });
<div id="main"></div>