Nabil Kadimi
Nabil Kadimi

Reputation: 10414

How to not repeat "obj." when invoking many methods on the same object?

I don't remember where I saw that you can replace calls like this:

my_obj.method_1();
my_obj.method_2();
my_obj.method_3();

With something like this:

some_construct (my_obj) {
    method_1();
    method_2();
    method_3();
}

Any idea on how to do this?

Note: I'm not looking for method chaining

Upvotes: 0

Views: 96

Answers (4)

Amit
Amit

Reputation: 46351

If you're goal is to "conserve" text, you could:

function callAll(o, funcs) {
  funcs.forEach(function(func) {
    o[func]();
    });
}

// Have an object...
var my_obj = {
  method1: function() {
    alert(1);
  },
  method2: function() {
    alert(2);
  },
  method3: function() {
    alert(3);
  }
}

// And now you can call multiple object methods like this:
callAll(my_obj, ['method1', 'method2', 'method3']);

So basically you have 1 short function that you can invoke with an object and a list of method names to call.

Upvotes: 1

Quentin
Quentin

Reputation: 944186

With with, but don't do it. It's confusing syntax at best, and is banned in strict mode (which you should be using).

var my_obj = {
  value: 0,
  foo: function() {
    this.value++
  },
  bar: function() {
    this.value += 2
  },
  baz: function() {
    alert(this.value)
  }
};

with(my_obj) {
  foo();
  bar();
  baz();
}

Upvotes: 2

user2357112
user2357112

Reputation: 281757

The construct is

with (my_obj) {
    ...
}

but don't use it! It's deprecated, since it makes it hard to see whether a name refers to an object property or a variable, and the check must be made repeatedly at runtime. "use strict"; actually prohibits with.

If you don't want to type as much, you can give the object you're using a shorter name:

o = my_obj;
o.method_1();
o.method_2();
o.method_3();

Upvotes: 1

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64943

In modern JavaScript there's no syntactic sugar for this.

At the end of the day, object-oriented programming doesn't like not being able to know to which object instance belongs a member by just reading the code.

The right way

There's a concept in object-oriented programming called encapsulation. If you need to simplify your code because you don't want to call a set of methods that should be called together, you need to encapsulate these calls into a more generic method:

var obj = {
    method1: function() {}, method2: function(), method3: function(),
    doAll: function() {
         this.method1();
         this.method2();
         this.method3();
    }
};

And later you just call obj.doAll() instead of each method one by one.

Upvotes: 1

Related Questions