如何检查匿名函数是否具有属性?

时间:2020-11-04 01:13:48

标签: javascript object properties anonymous-function

我已经用匿名函数编写了JavaScript,并具有一个属性:


!function(e) {
    for(;e.length;){
        e.shift()();
        console.log(e[0].hasOwnProperty('a');
    }
}

([(function(){
    this.a = function(){
        console.log("hello");
    }
}),
function(){
    //no property here
}]);

在控制台上打印e[0].hasOwnProperty('a')时出现错误

它表示:::::未捕获的TypeError:无法读取未定义的属性'hasOwnProperty'

我想阅读并检查数组参数中的匿名函数是否具有属性。

1 个答案:

答案 0 :(得分:0)

首先,您将第一个值移出后正在测试e[0],因此在最后一次迭代中,您将检查undefined,因为空数组e[0] === undefined

第二,this.a = value不会向函数添加属性-除非该函数的使用方式与new fn()类似,否则生成的对象将具有名为a的属性

可以

! function(e) {
  for (; e.length;) {
    const fn = e.shift();
    var o = new fn();
    console.log(o.hasOwnProperty('a'));
  }
}([function() {
    this.a = function() {
      console.log("hello");
    };
  },
  function() {
    //no property here
  }
]);

或者,您可以定义第一个函数,例如

(() => {
  const fn = function() { }; 
  fn.a = function(){ 
    console.log("hello"); 
  }; 
  return fn; 
})()

由谁来编写代码

! function(e) {
  for (; e.length;) {
    const fn = e.shift();
    //fn(); // you don't actually need to run it
    console.log(fn.hasOwnProperty('a'));
  }
}([(() => {
    const fn = function() {};
    fn.a = function() {
      console.log("hello");
    };
    return fn;
  })(),
  function() {
    //no property here
  }
]);

相关问题