supercell
supercell

Reputation: 309

Javascript - Difference between defineProperty and directly defining a function on an object

I recently created my own module for node.js for use with the koa module. It's a translation module like koa-i18n. I've studied other koa modules to see how functions/properties are applied to the koa context/request and some of them use the Object.defineProperty function, but what I did in my module was apply a function directly on 'this'.

So, what is the difference between using

Object.defineProperty(app.context, 'getSomeValue', { ... });

and

return function* (next) { this.getSomeValue = function () { ... } }

I've also come across the node-delegates module which uses the 'apply' function. Which of these methods is the preferred way of applying a function/property to an existing object and what are the pros and cons?

Upvotes: 3

Views: 1135

Answers (1)

Y123
Y123

Reputation: 977

The defineProperty method has specific advantages over directly setting a property in an object or returning a function object (which in some ways can simulate pesudo-private fields).

You can use defineProperty to define constants decide whether they are enumerable and more.

You can check-out a similar discussion here - when do you use Object.defineProperty().

Also do check out the examples from Mozilla Developer Network for this method and the configs for being able to decide whether the prop is writable, enumerable etc using define property.

Apply is a bit different and I think a better comparison would be with the JavaScript call method. It is similar to call with mostly schematic differences. See note here. Apply and Call can be used in a way to invoke a method - roughly like reflection in other languages like Java.

Upvotes: 1

Related Questions