0

I have some global object CD and it has set of properties as follows:

window.cd = {
  config:{
    title:"..."
  }
  a:func..., 
  b:56,
  c:..
}

I want user to allow add properties to cd and cd.config but properties cd.a, cd.b, cd.config.title to be sealed (no modification allowed) .

User should not be able to delete window.cd or these properties as well (Other properties he can delete or modify).

I tried with following:

window.cd.a.seal();
window.cd.b.seal();
window.cd.config.title.seal();

but it thrown following error:

window.cd.config.title.seal is not a function

Akhilesh Kumar
  • 9,085
  • 13
  • 57
  • 95
  • `Object.seal` is a function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal, `String.seal` is not (`window.cd.config.title` is a string) – Rob M. Aug 11 '17 at 15:35
  • So how to achieve my requirement I want to stop user to modify title. – Akhilesh Kumar Aug 11 '17 at 15:37
  • 2
    You have to seal an object, not individual properties of it. Also, sealing doesn't prevent changes in property value, it only keeps properties from being added or changed. Perhaps you want to mark them non-writeable https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty – Jason Fetterly Aug 11 '17 at 15:37
  • @JasonFetterly And how to prevent cd from deleting together with define property. – Akhilesh Kumar Aug 11 '17 at 15:52
  • You can't prevent window.cd from being deleted unless you put it inside of another object - 'window' cannot be sealed. – Jason Fetterly Aug 11 '17 at 16:27

1 Answers1

0

A quick sample making title unwritable

"use strict";
// Use strict mode or assignments to nonwritable properties silently fail

window.cd = {
  config:{
    title:'mytitle'
  },
  a:12,
  b:56
}

console.log(cd.config.title)
Object.defineProperty(cd.config,'title',{writable:false});
cd.config.title="Test";  // Fails, throws exception if Strict mode
console.log(cd.config.title)
Jason Fetterly
  • 182
  • 1
  • 12