sdinesh94
sdinesh94

Reputation: 1178

How to access the property function within a function object javascript

the following is the code I 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 be sorted", function(assert) {
    var sorted = sorter.sortNums(nums);
    assert.deepEqual(sorted, sortedNums, "Passed!");
});

My supposition are as follows:

  1. sorter is a function object referencing MakeSorter() function

  2. sortNums is a property of MakeSorter which turns out to be an object and hence has the function syntax

but it produces the error as expected ";" on the line where sortNums is declared.why?

Upvotes: 0

Views: 41

Answers (2)

Downgoat
Downgoat

Reputation: 14361

Perhaps you meant to use this:

var nums = [1, 5, 4, 2, 3];
var sortedNums = [1, 2, 3, 4, 5];

var MakeSorter = function () {
    this.sortNums = function(nums) {
        return this.nums.sort();
    }
};

var sorter = new MakeSorter();

QUnit.test("Numeric list can be sorted", function(assert) {
    var sorted = sorter.sortNums(nums);
    assert.deepEqual(sorted, sortedNums, "Passed!");
});

You seem to of got the idea that in JavaScript, functions are object, but slightly different. What you are trying to make is kind of like a JavaScript class. You are making function as regular, not an object. In order to add a function to a function use this. That's short for:

var MakeSorter = function () {
   //...
}

MakeSorter.sortNums = function (nums) {
    //...
}

Upvotes: 1

arcyqwerty
arcyqwerty

Reputation: 10675

This would set the property sortNums on sorter to the function that you provided. However, I'm not exactly sure what you are trying to do in accomplishing this and there may be a better way to design the behavior you're trying to 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 be sorted", function(assert) {
      var sorted = sorter.sortNums(nums);
      assert.deepEqual(sorted, sortedNums, "Passed!");
  });

In short, your syntax error seems to be that you are mixing up a function body declaration with an object literal. The statements inside a function body (between the { and }) are executed when the function is called. You cannot define properties on the function by adding them in object literal syntax { prop : value }.

var sorter = {
  sortNums: function(nums) {
      return this.nums.sort();
  }
};

might be more along the lines of what you are looking for if sorter does not need to be callable.

Upvotes: 0

Related Questions