T
T
Timokins2018-01-28 23:50:14
JavaScript
Timokins, 2018-01-28 23:50:14

Is there a difference in function calls?

const a = {
  b: function() {
    // 1 вариант
    a.с();
    // 2 вариант
    this.с();
  },

 c: function() {
  
  }
}

is either acceptable? or something bad manners here?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-01-29
@timokins

You have already been answered above about the pitfalls of using this in object methods.
But it is more correct to use this . Why? If you need to change the name of an object reference, or if you need to export an object as a module, you don't have to change the implementation of the methods. It also improves readability. Well, if the method needs to be transferred to another place, use bind :

const a = {
  b() {
    this.с();
  },
  c() {
    alert('expected result');
  }
}

const d = {
  b: a.b.bind(a),
  c() {
    alert('wow');
  }
};

d.b(); //  => "expected result"

The short form of object methods is more convenient and readable. Use it in your code.
Long form notation:
var obj = {
  a: function() { 
    // do something
  },
  b: function() { 
    // do something
  }
};

Short form of entry:
const obj = {
  a() {
    // do something
  },
  b() {
    // do something
  }
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question