Skip to content Skip to sidebar Skip to footer

Understanding Intl.datetimeformat As A Javascript Object

I do not understand the behavior of Intl.DateTimeFormat. It does not expose the behavior I would expect from a JavaScript object. I would like to understand why? The following sni

Solution 1:

Original answer

Well, since it's a built-in object - it is good to have it frozen. But you can do things like this just in Javascript with Object.defineProperty.

See the following snipper. You can prevent override of your properties with writeable: false. (I've used JS 5.1)

varMyCoolConstructor = function () {

  Object.defineProperty(this, 'nonWriteable', {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function () {return42;}
  });
};

var instance = newMyCoolConstructor();


console.log(instance.nonWriteable()); //42
instance.nonWriteable = function () {return'overriden';}
console.log(instance.nonWriteable()); //42

How to prevent prototypal inheritance?

Check this simple snippet. You can just check if current context have the same prototype as your constructor.

varMyCoolConstructor = function () {
  this.foo = function () {
    if (Object.getPrototypeOf(this) === MyCoolConstructor.prototype) {
      return42;
    } else {
      thrownewError('bad this');
    }
  };
};

var instance = newMyCoolConstructor();
console.log(instance.foo());
//42var instance2 = Object.create(instance);
console.log(instance2.foo())
//Bad this

Edit 2

Derived object method override can also be prevented in the same manner, they derive property config. Check this snippet which is combination of previous 2

varMyCoolConstructor = function () {
  Object.defineProperty(this, 'foo', {
    value: function () {
      if (Object.getPrototypeOf(this) === MyCoolConstructor.prototype) {
        return42;
      } else {
        thrownewError('bad this');
      }
    },
    writeable: false
  });
};

var instance = newMyCoolConstructor();
console.log(instance.foo());
//42var derivedInstance = Object.create(instance);
derivedInstance.foo = function () {
  return'overriden';
};
console.log(derivedInstance.foo());
//Bad this. Can't be overridden because foo property is not writeable

Not cool hacks in 3.. 2.. 1..

If you really want to override smth, Object.defineProperty come to the rescue.

const itDateTimeFormat2 = newwindow.Intl.DateTimeFormat('it-CH');
const wrappedDateTimeFormat = Object.create(itDateTimeFormat2);
Object.defineProperty(wrappedDateTimeFormat, 'format', {value: function(date) { return'Overridden!' + date.toString(); }})
wrappedDateTimeFormat.format()
//"Overriden! ..."

Conclusion

As we've seen with the examples. System objects behaves just like normal configured javascript objects

Post a Comment for "Understanding Intl.datetimeformat As A Javascript Object"