Properties
A property is similar to a field except that you do not have to use additional methods to manage your private fields.
Auto Implemented Properties
Adding the public keyword.
class myClass {
constructor(public property_name: string) {}
}
let myObject = new myClass("Monday");
console.log( myObject.property_name ) // "Monday"
replaces
class myClass {
property_name: string;
constructor(name: string) {
this.property_name = name;
}
}
let myObject = new myClass("Monday");
console.log( myObject.property_name ) // "Monday"
Accessing
You can access properties using a string value
All the keys are converted to string type in the square bracket
myObject.Property1
myObject['Property 2']
myObject[''] //blank string
var myString = 'Property3';
myObject[myString] // you can use variables
var myNumber = math.random();
myObject[myNumber]
var myObject2 = new Object();
myObject[myObject2] // this uses myObject2.toString()
var myObject = {
Property1 : 10,
get Property1_Get() {
return this.Property1;
}
}
var myObject = {
Property1 : 10,
set Property1_Set(val) {
this.Property1 = val;
}
}
Properties
function class_Example(name, address) {
// private fields
var _name = "some text";
Object.defineProperty(this, "name",
get: function() { return _name; }
set: function(value) { _name = value; }
});
}
var myObject = new class_Example("one","two");
var string1 = myObject.name
Add Properties Dynamically
You can add properties to an object by just defining them
myobject.Property_AnotherOne = "something else";
All object properties are mutable, ie changeable
Assigning Properties
function myFunction(arg1, arg2, arg3) {
myFunction.Property_Value1 : arg1;
myFunction.Property_Value2 : arg2;
myFunction.Property_Value3 : arg3;
}
function myFunction(arg1, arg2, arg3) {
myFunction.Property_Value1 = arg1;
myFunction.Property_Value2 = arg2;
myFunction.Property_Value3 = arg3;
}
The 'this' keyword is used inside a function to refer to the object the function is contained within.
Which is also equivalent to
function myFunction(arg1, arg2, arg3) {
this.Property_Value1 : arg1;
this.Property_Value2 : arg2;
this.Property_Value3 : arg3;
}
This is equivalent to
function myFunction(arg1, arg2, arg3) {
this.Property_Value1 = arg1;
this.Property_Value2 = arg2;
this.Property_Value3 = arg3;
}
This is equivalent to
Enumerating
for - in was added in ES 2009
This traverses all enumerable properties of an object
var Utilities = {
Method_ShowAllMembers : function(targetObject) {
for (member in targetObject) {
document.write("<br />" + targetObject[member]);
}
}
Method_ShowAllMembersAndValues : function(targetObject) {
for (member in targetObject) {
document.write("<br />" + member + " == > " + targetObject[member]);
}
}
}
Utilities.Method_ShowAllMembers(myObject);
Utilities.Method_ShowAllMembersAndValues(myObject);
Object.keys(myObject)
Object.getOwnPropertyNames(myObject)
© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext