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) + "%";
?如果是这样,您将如何做?
答案 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));