0
var sampleFunction = function() {
var self = this;
console.log(self.somevalue);
console.log(?); //output : 2
};

sampleFunction().bind(this,2);

how to access this value 2 inside that samplefunction.

robieee
  • 364
  • 2
  • 18
  • 1
    It should be `sameplFunction2 = sampleFunction.bind(this, 2)` or just bind it when you are declaring it. – Sachin Jain Dec 04 '13 at 06:17
  • 1
    Please read the docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind . Your code won't work as-is anyways, because you're calling `.bind()` on `undefined`. The arguments passed to `bind` will be provided in the parameters of the function – Ian Dec 04 '13 at 06:17

2 Answers2

2

You need to create a new function like so

var boundFunction = sampleFunction.bind(this);

boundFunction(2)

It's often easiest to use function.call like this answer

 sampleFunction.call(this, 2);
Community
  • 1
  • 1
actual_kangaroo
  • 5,971
  • 2
  • 31
  • 45
1

If what you're trying to do is to create a new function that will always call sampleFunction and pass it an argument of 2, then you would do that like this:

// define sampleFunction with one argument
var sampleFunction = function(data) {
    console.log(data);
}

// create a new function that always calls sampleFunction 
//     with a value for this and a particular argument
var newFunc = sampleFunction.bind(this, 2);

// call that new function
newFunc();   // will put 2 in the console

I would also recommend reading the MDN doc page on .bind() so you can get a better description of what it does and how to use it.

Since you haven't provided any context for what you're really trying to do, you could also get the same result as above with either of these:

sampleFunction(2);
sampleFunction.call(this, 2);

If this is not what you're trying to do, then back way, way up and describe what you are actually trying to accomplish

jfriend00
  • 683,504
  • 96
  • 985
  • 979