Object has no method 'apply'

前端 未结 1 485
故里飘歌
故里飘歌 2021-01-06 03:26

I am creating a few DOM elements dynamically like,

var anchorElement = jQuery(\'\',{text:property.text});
var liElement = jQuery(\'
  • \',
  • 1条回答
    •  萌比男神i
      2021-01-06 04:05

      Update:

      Youve said that property.actfn is a string, "paySomeoneClick". It's best not to use strings for event handlers, use functions instead. If you want the function paySomeoneClick, defined in the string, to be called, and if that function is global, you can do this:

      anchorElement.on('click',function(event) {
          return window[property.fnctn](event);
      });
      

      That works because global functions are properties of the global object, which is available via window on browsers, and because of the bracketed notation described below.

      If the function is on an object you have a reference to, then:

      anchorElement.on('click',function(event) {
          return theObject[property.fnctn](event);
      });
      

      That works because in JavaScript, you can access properties of objects in two ways: Dotted notation with a literal property name (foo.bar accesses the bar propety on foo) and bracketed notation with a string property name (foo["bar"]). They're equivalent, except of course in the bracketed notation, the string can be the result of an expression, including coming from a property value like property.fnctn.

      But I would recommend stepping back and refactoring a bit so you're not passing function names around in strings. Sometimes it's the right answer, but in my experience, not often. :-)

      Original answer:

      (This assumed that property.fnctn was a function, not a string. But may be of some use to someone...)

      The code

      anchorElement.on('click',property.fnctn);
      

      will attach the function to the event, but during the call to the function, this will refer to the DOM element, not to your property object.

      To get around that, use jQuery's $.proxy:

      anchorElement.on('click',$.proxy(property.fnctn, property));
      

      ...or ES5's Function#bind:

      anchorElement.on('click',property.fnctn.bind(property));
      

      ...or a closure:

      anchorElement.on('click',function(event) {
          return property.fnctn(event);
      });
      

      More reading (on my blog):

      • Mythical methods
      • You must remember this
      • Closures are not complicated

      0 讨论(0)
    提交回复
    热议问题