I have the following:
getitem: function(){
$this.users = $data.data;
$this.users = $this.users.filter( function(item) {
if(item.status === true ) {
if( item.children.length > 0 ){
item.children = this.getChildrem(item.children, true);
}
return item;
}});
},
getChildrem: function(node, estatus){
$children = node.filter( function(item) {
if(item.status === estatus ) {
if( item.children.length > 0 ){
item.children = this.getChildrem(item.children, estatus);
}
return item;
}});
return $children;
},
this is a simple function recursive, I just get all items(parents and chlidren) with status 'true'but I'm having this error:
Uncaught (in promise) TypeError: this.getChildrem is not a function
Why I'm getting this error???
CodePudding user response:
When you define the function that you pass into node.filter
, the this
context changes. You can avoid this by passing in an arrow function instead, or using .bind
.
So instead of
getChildrem: function(node, estatus){
$children = node.filter( function(item) {
try this:
getChildrem: function(node, estatus){
$children = node.filter( (item) => {
CodePudding user response:
It's because the callback function is using the global scope, while that object is in a different scope
var obj = {
test(){
(function(){console.log(this);})(); //Prints global object
(()=>{console.log(this);})(); // prints local object
}
}
You would need to change that normal function to an arrow function,because the arrow function will capture the enclosing scope