Reputation: 67
Whats the difference between defining a method on an object like o.x and o.y?
o = {
x: function () {
console.log('hi')
},
y () {
console.log('bye')
}
}
Upvotes: 3
Views: 78
Reputation: 15268
One of the goals was to provide syntactic sugar to bring Javascript closer to class syntax features: https://babeljs.io/docs/en/learn/#enhanced-object-literals
Object literals are extended to support setting the prototype at construction, shorthand for foo: foo assignments, defining methods and making super calls. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.
super
also behaves differently. This is on the level of language semantics, not at runtime.
In relation to the nature of methods, differences are related to inheritance and class features, since it was introduced with the introduction of class syntax.
Babel transpiled version of code
// logs 'method 1'
var obj1 = { method1:()=>console.log('method 1') }
var obj2 = {
method2() {
super.method1();
}
}
Object.setPrototypeOf(obj2, obj1);
obj2.method2();
This throws a syntax error and will not work, because super does not have meaning here:
var obj1 = { method1:()=>console.log('method 1') }
var obj2 = {
method2: function() {
super.method1(); // throws syntax erro
}
}
Object.setPrototypeOf(obj2, obj1);
obj2.method2();
Upvotes: 0
Reputation: 370679
The y() {
syntax is generally called a method.
The only real difference in modern environments is that a method cannot be instantiated with new
, but function
s can:
const o = {
x: function () {
console.log('hi')
},
y () {
console.log('bye')
}
};
new o.x();
new o.y();
Uncaught TypeError: o.y is not a constructor @ JS line 11
This is ES2015 syntax, though. Ancient environments like IE11 do not support method syntax (or arrow functions, or many other nice things).
Upvotes: 5