鍍金池/ 問答/HTML/ ES6 修改通過方法修改屬性為啥這么詭異?!

ES6 修改通過方法修改屬性為啥這么詭異?!

class Text {
    constructor(str) {
        this.str = str;
        this.bold = false;
        this.setupBold = (model) => {
            console.log(this === model)
        }
    }
}

 redux 調(diào)用 text.setupBold(text); 

打印的是false,model 和 this 不是同一個內(nèi)存對象?為何會這樣


問題解決了,出現(xiàn)這個問題是因為我在 redux 中 copy 對象用 text = {...text},這樣拷貝出來的對象有問題,會導致 text 的函數(shù)找不到,所以就用箭頭函數(shù)綁定了個函數(shù)變量,箭頭函數(shù)的這個 this 是指向的 類。

拷貝對象換成下面這個

function clone(origin) {
  let originProto = Object.getPrototypeOf(origin);
  return Object.assign(Object.create(originProto), origin);
}

然后這樣就好了

class Text {
    constructor(str) {
        this.str = str;
        this.bold = false;
    }
    
    setupBold(model) {
        console.log(this === model)
    }
}
回答
編輯回答
愚念

class里面定義方法,不能用this.的形式啊。 直接定義setupBold就好了。

2018年8月2日 22:56
編輯回答
幼梔

你方法定義的時候是用的this.setupBold 方法里的this指向的是class這個類對象,而不是類的實例,正確的寫法應該是


class Text {
    constructor(str) {
        this.str = str;
        this.bold = false;
    }
    
    setupBold = (model) => {
      console.log(this === model)
    }
}
2018年4月29日 01:24
編輯回答
青黛色

建議題主還是從語法來理解這個問題,這跟類無關,純粹是語法問題。

首先你這個寫法就有問題啊,這個能跑么?我直接在 node 下面跑會報錯。正確的寫法是這樣吧:

class Text {
  constructor(str) {
    this.str = str;
    this.bold = false;
    
    this.setupBold = (model) => {
      console.log(this === model)
    }
  }
}

這樣的話,你給類的實例增加了一個方法 setupBold,但是這個方法使用的是箭頭函數(shù),也就是綁定了 this 的函數(shù),它的 this 是它誕生的環(huán)境也就是你聲明類 Text 的環(huán)境,當然和實例化之后的 this 不是一個對象咯。

改成這樣即可:

class Text {
  constructor(str) {
    this.str = str;
    this.bold = false;
  }
    
  setupBold(model) {
    console.log(this === model)
  }
}
2017年4月19日 19:18