@
@
@zipo2012-02-14 17:34:54
JavaScript
@zipo, 2012-02-14 17:34:54

JavaScript: Passing not just a function, but an entire object with its properties?

function TestClass(prop) {
    if (prop) {
      parms = prop;
    }
  }

  TestClass.prototype = {
    constructor: TestClass,
    parms: 'test',
    var1: 2,

    fnc: function () {
      alert(this.var1);
    }
  }

  function fnc2(msg) {
    test = new TestClass('11');
    var myFnc = test.fnc;
    myFnc();
  }

on pressing the button, we call fnc2, where the object's function code is assigned to the myFnc variable. The example is remote, it’s clear that it is in this case that you can call test.fnc (), but in fact I need to pass test.fnc as a parameter so that another object calls the function code, but the object itself is also needed.
Is it possible to call the function of the object test.fnc by myFnc() and also have a whole object with its properties?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stdit, 2012-02-14
_

There are no classes in JS, and this is not a reference to an object, but an execution context. You can use closures if you need some properties inside objects, like this:

function foo(param){
    var a = param;
    this.getA = function(){
        return a;
    };
    this.setA = function(p){
        a = p;
    };
}
var f = new foo(123);
g = f.getA();
console.log(g());

K
Konstantin Kitmanov, 2012-02-14
@k12th

You need to fix the execution context of some function. This is done using Function.prototype.bind from ES5. There are polyfills in underscore.js and jQuery - _.bind and $.proxy respectively.

A
Anatoly, 2012-02-14
@taliban

Could you rephrase the question? Especially the last part of it, because it is not clear what exactly you want to get.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question