从对象上的方法访问对象属性

时间:2020-10-29 14:04:53

标签: javascript json

我有一个json对象,如下;

export const initialState = {

    name: '',
    acceptable: false,
    identified: false,
    variation: false,
    variationText: () => {
      return name.toUpperCase() //as an example
    }
    
}


//use it kind of like this, so that the item's properties are transposed, but any missing attributes
//or the methods are maintained.
return {...initialState, ...item}

当我尝试访问方法中的属性时,它不可用。

谢谢。

1 个答案:

答案 0 :(得分:2)

JavaScript不像其他语言那样具有任何形式的隐式purchase_units[0].invoice_id,才能访问对象的属性,您必须显式引用该对象(除非您使用不赞成使用的this语句)。

在您的示例中,您将使用常量的名称:

with

旁注:export const initialState = { name: '', acceptable: false, identified: false, variation: false, variationText: () => { return initialState.name.toUpperCase() // ^^^^^^^^^^^^^ } } 不是代码中的方法,它是绑定到属性的箭头函数。这很重要,因为如果它是一种方法,则除了如上所述使用variationText外,还可以(取决于调用该方法的方式)使用initialState。但是您不能将箭头功能分配给属性,因为箭头功能 close over this,因此无法通过调用函数的方式来设置它们。 (More here。)

因此,如果您将其设为方法,并且如果以通常的方式调用了该方法,则可以使用this

this

但是可以用错误的export const initialState = { name: '', acceptable: false, identified: false, variation: false, variationText() { // ^^^^^^^^^^^^^^^^^ return this.name.toUpperCase() // ^^^^^ } } 来调用该方法; details herehere