【问题标题】:How can I check if an anonymous function has a property?如何检查匿名函数是否具有属性?
【发布时间】:2020-11-04 01:13:48
【问题描述】:

我用匿名函数编写了一个 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') 打印到控制台时出现错误

它说::::Uncaught TypeError: Cannot read property 'hasOwnProperty' of undefined

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

【问题讨论】:

  • 问题是,一旦你 e.shift() 第二次,e[0] 是未定义的 - 你也跳过了 console.log(e.....) 中的第一个函数,这就是你看不到它输出的原因
  • 另一个问题是,这些函数都不会拥有a 的属性
  • 那么如何在匿名函数中添加属性呢?
  • 定义它们时......你不能(不太正确,你可以做一个 IIFE)......但是在你的代码中,e[0].a = "propertyValue"
  • IIFE ...使用属性创建函数...即数组中的第一个...(() => { const fn = function() { }; fn.a = function(){ console.log("hello"); }; return fn; })()

标签: javascript object properties anonymous-function


【解决方案1】:

首先,您在将第一个值移出后测试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
  }
]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多