Javascript 如何在属于同一对象的方法的函数中使用对象属性?
我有一个对象,它有一个方法。在这个方法中有一个函数,我想在这个方法的函数中使用我的object属性 这就是我现在正在做的:Javascript 如何在属于同一对象的方法的函数中使用对象属性?,javascript,Javascript,我有一个对象,它有一个方法。在这个方法中有一个函数,我想在这个方法的函数中使用我的object属性 这就是我现在正在做的: const obj ={ property: 5, method(){ //deconstructing this obj const {property} = this; // a function inside a method const func1 = () =>{ console.log(property + 5
const obj ={
property: 5,
method(){
//deconstructing this obj
const {property} = this;
// a function inside a method
const func1 = () =>{
console.log(property + 5);
}
}
}
我在其方法中解构了obj,因为当我在方法的函数中使用obj属性时,我不想继续执行
this.property
或obj.property
。这不好吗?还有更好的方法吗?抓取这样一个属性值的本地副本就可以了。请注意,它是值的副本,因此,如果方法或它调用的方法中的某些内容更改了属性值,您将不会在本地副本中看到该更改。例如:
const obj={
财产:“原件”,
方法(){
const{property}=this;
log(`property=${property},this.property=${this.property}`);
this.changeProperty()
log(`property=${property},this.property=${this.property}`);
},
changeProperty(){
this.property=“UPDATED”;
}
};
obj.method()代码>获取这样一个属性值的本地副本就可以了。请注意,它是值的副本,因此,如果方法或它调用的方法中的某些内容更改了属性值,您将不会在本地副本中看到该更改。例如:
const obj={
财产:“原件”,
方法(){
const{property}=this;
log(`property=${property},this.property=${this.property}`);
this.changeProperty()
log(`property=${property},this.property=${this.property}`);
},
changeProperty(){
this.property=“UPDATED”;
}
};
obj.method()代码>感谢您的快速反馈!我不知道它实际上只是复制了房产的价值。@JohnHinrichJosephG.Galindo-我的荣幸!是的,这是一份拷贝,但通常情况下这是绝对好的。FWIW,在React中class
组件的render
方法中可以看到很多这样的情况,比如:const{a,b,c}=this.state然后在返回的元素中使用a
、b
和c
。快乐编码!感谢您的快速反馈!我不知道它实际上只是复制了房产的价值。@JohnHinrichJosephG.Galindo-我的荣幸!是的,这是一份拷贝,但通常情况下这是绝对好的。FWIW,在React中class
组件的render
方法中可以看到很多这样的情况,比如:const{a,b,c}=this.state然后在返回的元素中使用a
、b
和c
。快乐编码!