2

Right now, I'm doing something like this:

var myObject = {}

const action = () => {
    console.log("say hello")
}

myObject.act = action

This results in the output:

say hello

But is there a faster way to do this, like a const lambda (or something)?

Much like:

// This is psuedocode.
myObject.myConstAction = const lambda (){
    console.log("I won't change.")
}

I would hope the property .myConstAction cannot be reassigned or overwritten.

1
  • To make a constant function property, you have to use Object.defineProperty(myObject, "act", {writable: false, enumerable: true, configurable: false, value: () => console.log("say hello")});. const doesn’t help here. Commented Mar 31, 2018 at 8:09

2 Answers 2

4

You're mistaken in what the code you have does.

action is a constant, and its value cannot be changed.

myObject.act is assigned a copy of the value of action (i.e. another reference to the same function). There is nothing constant about myObject.act.


You can assign a function to act and make the property read only like so:

var myObject = {}
Object.defineProperty(myObject, "act", {
  value: action = () => {
    console.log("say hello");
  },
  writable: false
});

myObject.act();
// The next line has no effect because the property is not writable
myObject.act = () => console.log("Overwritten!");
myObject.act();

Sign up to request clarification or add additional context in comments.

2 Comments

Also, add configurable: false to prohibit overwriting myObject.act with another Object.defineProperty.
@Quentin this is exactly what I was looking for. But can you add configurable: false to your answer or explain why you wouldn't need it or want it? Thanks!
2

There's not really any such thing as a "const function" (or a const anything) that's a property of an object. The quickest way is still

myObject.act = () => console.log('say hello');

See how the const identifier doesn't really do anything:

const myObject = {}
const action = () => {
    console.log("say hello")
}
myObject.act = action;


myObject.act = () => console.log('goodbye');
myObject.act();

5 Comments

So a const object can have variable properties?
Reassignment and mutation are completely different concepts. const means that the variable name on the left-hand side of the = can never be reassigned - and that's all.
@NonCreature0714 To make an object non-mutable (its own properties, but not nested properties), apply Object.freeze to it.
@Xufox that you for that very useful link about Object.freeze
I think this answer demonstrates the limits of const effectively.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.