How to access the property function within a function object javascript -
the following code have written
var nums = [1, 5, 4, 2, 3]; var sortednums = [1, 2, 3, 4, 5]; var sorter = function makesorter() { 'sortnums': function(nums) { return this.nums.sort(); }; }; qunit.test("numeric list can sorted", function(assert) { var sorted = sorter.sortnums(nums); assert.deepequal(sorted, sortednums, "passed!"); });
my supposition follows:
sorter function object referencing makesorter() function
sortnums property of makesorter turns out object , hence has function syntax
but produces error expected ";" on line sortnums declared.why?
this set property sortnums
on sorter
function provided. however, i'm not sure trying in accomplishing , there may better way design behavior you're trying accomplish.
var nums = [1, 5, 4, 2, 3]; var sortednums = [1, 2, 3, 4, 5]; var sorter = function makesorter() {}; sorter.sortnums = function(nums) { return this.nums.sort(); }; qunit.test("numeric list can sorted", function(assert) { var sorted = sorter.sortnums(nums); assert.deepequal(sorted, sortednums, "passed!"); });
in short, syntax error seems mixing function body declaration object literal. statements inside function body (between {
, }
) executed when function called. cannot define properties on function adding them in object literal syntax { prop : value }
.
var sorter = { sortnums: function(nums) { return this.nums.sort(); } };
might more along lines of looking if sorter not need callable.
Comments
Post a Comment