jquery - Accessing javascript object's properties in the method -


for below code snippet expecting answer "number" getting "undefined". can please me here find out why returning "undefined" ?

var foo = {     bar: function () {         return this.baz;     },     baz: 1 };  (function () {     return typeof arguments[0](); //this return "undefined" })(foo.bar); 

if typeof foo.bar(), give me expected answer "number".

thanks in advance.

that's because this normal functions set how function called, not it's defined. (ecmascript2015's "arrow" functions different, inherit this they're created, not how they're called.)

you have couple of options:

1) use function#bind create new function that, when called, call original function correct this:

var foo = {    bar: function() {      return this.baz;    },    baz: 1  };  (function() {    snippet.log(typeof arguments[0]());  })(foo.bar.bind(foo));
<!-- script provides `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->  <script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

2) use own wrapper function:

var foo = {    bar: function() {      return this.baz;    },    baz: 1  };  (function() {    snippet.log(typeof arguments[0]());  })(function() {    return foo.bar.apply(foo, arguments);  });
<!-- script provides `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->  <script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -