Posts

Showing posts with the label Properties

"Computed" Property In Typescript

Answer : If it's an interface then there's no syntax, because all properties in JavaScript can have getter/setter functions instead of being exposed fields. It's an implementation concern. BTW members in TypeScript use camelCase not TitleCase : export interface Person { // get + set: firstName: string; lastName : string; jobTitle : string; // get-only: readonly fullName : string; } class SimplePerson implements Person { public firstName: string; // value-property (“field”) public lastName: string; public jobTitle: string; get fullName(): string { // read-only property with getter function (this is not the same thing as a “function-property”) return this.firstName + " " + this.lastName; } } I note that it is confusing that TypeScript's designers chose to use the keyword readonly to denote "readable" properties in an interface when it doesn't actually prohibit an implementation from also havi...

Can I Loop Through A Javascript Object In Reverse Order?

Answer : Javascript objects don't have a guaranteed inherent order, so there doesn't exist a "reverse" order. 4.3.3 Object An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method. Browsers do seem to return the properties in the same order they were added to the object, but since this is not standard, you probably shouldn't rely on this behavior. A simple function that calls a function for each property in reverse order as that given by the browser's for..in, is this: // f is a function that has the obj as 'this' and the property name as first parameter function reverseForIn(obj, f) { var arr = []; for (var key in obj) { // add hasOwnPropertyCheck if needed arr.push(key); } for (var i=arr.length-1; i>=0; i--) { f.call(obj, arr[i]); } } //usage reverseFo...