无论如何,有没有一个函数可以告诉某个状态在Javascript中有状态?

时间:2020-04-23 15:53:53

标签: javascript function variables functional-programming closures

a = function() {
    if(this.n === undefined) {
        this.n = 0;
    }
    this.n += 1;
    return(this.b);
}
b = function() {
    return(5);
}

在这种情况下,a将是有状态的,而b将是无状态的。是否可以在JavaScript中创建函数hasSate(f),如果它的状态如true,则返回a,如果状态不像false,则返回b elmnt.style.right = toperecent((window.innerWidth - e.clientX), window.innerWidth) + "%"; ?如果是这样,您将如何做?

1 个答案:

答案 0 :(得分:0)

您可以创建函数的实例,并使用Object.getOwnPropertyNames函数检查是否有与该新实例关联的propertyNames。

let a = function() {
    if(this.n === undefined) {
        this.n = 0;
    }
    this.n += 1;
    return b();
}
let b = function() {
    return 5;
}


function hasState(fn) {
  let x = new fn();
  if(Object.getOwnPropertyNames(x).length > 0) {
     return true;
  }
  return false;
}

console.log(hasState(a))
console.log(hasState(b));

相关问题