Object C Property Assignments

JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method. In addition to objects that are predefined in the browser, you can define your own objects. This chapter describes how to use objects, properties, functions, and methods, and how to create your own objects.

Objects overview

Objects in JavaScript, just as in many other programming languages, can be compared to objects in real life. The concept of objects in JavaScript can be understood with real life, tangible objects.

In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight, a material it is made of, etc. The same way, JavaScript objects can have properties, which define their characteristics.

Objects and properties

A JavaScript object has properties associated with it. A property of an object can be explained as a variable that is attached to the object. Object properties are basically the same as ordinary JavaScript variables, except for the attachment to objects. The properties of an object define the characteristics of the object. You access the properties of an object with a simple dot-notation:


Like all JavaScript variables, both the object name (which could be a normal variable) and property name are case sensitive. You can define a property by assigning it a value. For example, let's create an object named and give it properties named , , and as follows:

var myCar = new Object(); myCar.make = 'Ford'; myCar.model = 'Mustang'; myCar.year = 1969;

Unassigned properties of an object are (and not ).

myCar.color; // undefined

Properties of JavaScript objects can also be accessed or set using a bracket notation (for more details see property accessors). Objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it. So, for example, you could access the properties of the object as follows:

myCar['make'] = 'Ford'; myCar['model'] = 'Mustang'; myCar['year'] = 1969;

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime). Examples are as follows:

// four variables are created and assigned in a single go, // separated by commas var myObj = new Object(), str = 'myString', rand = Math.random(), obj = new Object(); myObj.type = 'Dot syntax'; myObj['date created'] = 'String with space'; myObj[str] = 'String value'; myObj[rand] = 'Random Number'; myObj[obj] = 'Object'; myObj[''] = 'Even an empty string'; console.log(myObj);

Please note that all keys in the square bracket notation are converted to String type, since objects in JavaScript can only have String type as key type. For example, in the above code, when the key is added to the , JavaScript will call the method, and use this result string as the new key.

You can also access properties by using a string value that is stored in a variable:

var propertyName = 'make'; myCar[propertyName] = 'Ford'; propertyName = 'model'; myCar[propertyName] = 'Mustang';

You can use the bracket notation with to iterate over all the enumerable properties of an object. To illustrate how this works, the following function displays the properties of the object when you pass the object and the object's name as arguments to the function:

function showProps(obj, objName) { var result = ''; for (var i in obj) { // obj.hasOwnProperty() is used to filter out properties from the object's prototype chain if (obj.hasOwnProperty(i)) { result += objName + '.' + i + ' = ' + obj[i] + '\n'; } } return result; }

So, the function call would return the following:

myCar.make = Ford myCar.model = Mustang myCar.year = 1969

Enumerate the properties of an object

Starting with ECMAScript 5, there are three native ways to list/traverse object properties:

  • loops
    This method traverses all enumerable properties of an object and its prototype chain

  • This method returns an array with all the own (not in the prototype chain) enumerable properties' names ("keys") of an object .

  • This method returns an array containing all own properties' names (enumerable or not) of an object .

Before ECMAScript 5, there was no native way to list all properties of an object. However, this can be achieved with the following function:

function listAllProperties(o) { var objectToInspect; var result = []; for(objectToInspect = o; objectToInspect !== null; objectToInspect = Object.getPrototypeOf(objectToInspect)) { result = result.concat(Object.getOwnPropertyNames(objectToInspect)); } return result; }

This can be useful to reveal "hidden" properties (properties in the prototype chain which are not accessible through the object, because another property has the same name earlier in the prototype chain). Listing accessible properties only can easily be done by removing duplicates in the array.

Creating new objects

JavaScript has a number of predefined objects. In addition, you can create your own objects. You can create an object using an object initializer. Alternatively, you can first create a constructor function and then instantiate an object invoking that function in conjunction with the operator.

Using object initializers

In addition to creating objects using a constructor function, you can create objects using an object initializer. Using object initializers is sometimes referred to as creating objects with literal notation. "Object initializer" is consistent with the terminology used by C++.

The syntax for an object using an object initializer is:

var obj = { property_1: value_1, // property_# may be an identifier... 2: value_2, // or a number... // ..., 'property n': value_n }; // or a string

where is the name of the new object, each is an identifier (either a name, a number, or a string literal), and each is an expression whose value is assigned to the . The and assignment is optional; if you do not need to refer to this object elsewhere, you do not need to assign it to a variable. (Note that you may need to wrap the object literal in parentheses if the object appears where a statement is expected, so as not to have the literal be confused with a block statement.)

Object initializers are expressions, and each object initializer results in a new object being created whenever the statement in which it appears is executed. Identical object initializers create distinct objects that will not compare to each other as equal. Objects are created as if a call to were made; that is, objects made from object literal expressions are instances of .

The following statement creates an object and assigns it to the variable if and only if the expression is true:

if (cond) var x = {greeting: 'hi there'};

The following example creates with three properties. Note that the property is also an object with its own properties.

var myHonda = {color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}};

You can also use object initializers to create arrays. See array literals.

Using a constructor function

Alternatively, you can create an object with these two steps:

  1. Define the object type by writing a constructor function. There is a strong convention, with good reason, to use a capital initial letter.
  2. Create an instance of the object with .

To define an object type, create a function for the object type that specifies its name, properties, and methods. For example, suppose you want to create an object type for cars. You want this type of object to be called , and you want it to have properties for make, model, and year. To do this, you would write the following function:

function Car(make, model, year) { this.make = make; this.model = model; this.year = year; }

Notice the use of to assign values to the object's properties based on the values passed to the function.

Now you can create an object called as follows:

var mycar = new Car('Eagle', 'Talon TSi', 1993);

This statement creates and assigns it the specified values for its properties. Then the value of is the string "Eagle", is the integer 1993, and so on.

You can create any number of objects by calls to . For example,

var kenscar = new Car('Nissan', '300ZX', 1992); var vpgscar = new Car('Mazda', 'Miata', 1990);

An object can have a property that is itself another object. For example, suppose you define an object called as follows:

function Person(name, age, sex) { this.name = name; this.age = age; this.sex = sex; }

and then instantiate two new objects as follows:

var rand = new Person('Rand McKinnon', 33, 'M'); var ken = new Person('Ken Jones', 39, 'M');

Then, you can rewrite the definition of to include an property that takes a object, as follows:

function Car(make, model, year, owner) { this.make = make; this.model = model; this.year = year; this.owner = owner; }

To instantiate the new objects, you then use the following:

var car1 = new Car('Eagle', 'Talon TSi', 1993, rand); var car2 = new Car('Nissan', '300ZX', 1992, ken);

Notice that instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects and as the arguments for the owners. Then if you want to find out the name of the owner of car2, you can access the following property:


Note that you can always add a property to a previously defined object. For example, the statement

car1.color = 'black';

adds a property to car1, and assigns it a value of "black." However, this does not affect any other objects. To add the new property to all objects of the same type, you have to add the property to the definition of the object type.

Using the method

Objects can also be created using the method. This method can be very useful, because it allows you to choose the prototype object for the object you want to create, without having to define a constructor function.

// Animal properties and method encapsulation var Animal = { type: 'Invertebrates', // Default value of properties displayType: function() { // Method which will display type of Animal console.log(this.type); } }; // Create new animal type called animal1 var animal1 = Object.create(Animal); animal1.displayType(); // Output:Invertebrates // Create new animal type called Fishes var fish = Object.create(Animal); fish.type = 'Fishes'; fish.displayType(); // Output:Fishes


All objects in JavaScript inherit from at least one other object. The object being inherited from is known as the prototype, and the inherited properties can be found in the object of the constructor. See Inheritance and the prototype chain for more information.

Indexing object properties

You can refer to a property of an object either by its property name or by its ordinal index. If you initially define a property by its name, you must always refer to it by its name, and if you initially define a property by an index, you must always refer to it by its index.

This restriction applies when you create an object and its properties with a constructor function (as we did previously with the object type) and when you define individual properties explicitly (for example, ). If you initially define an object property with an index, such as , you subsequently refer to the property only as .

The exception to this rule is objects reflected from HTML, such as the array. You can always refer to objects in these arrays by either their ordinal number (based on where they appear in the document) or their name (if defined). For example, if the second tag in a document has a attribute of "myForm", you can refer to the form as or or .

Defining properties for an object type

You can add a property to a previously defined object type by using the property. This defines a property that is shared by all objects of the specified type, rather than by just one instance of the object. The following code adds a property to all objects of type , and then assigns a value to the property of the object .

Car.prototype.color = null; car1.color = 'black';

See the property of the object in the JavaScript reference for more information.

Defining methods

A method is a function associated with an object, or, simply put, a method is a property of an object that is a function. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object. See also method definitions for more details. An example is:

objectName.methodname = function_name; var myObj = { myMethod: function(params) { // ...do something   }   // OR THIS WORKS TOO   myOtherMethod(params) {   // ...do something else } };

where is an existing object, is the name you are assigning to the method, and is the name of the function.

You can then call the method in the context of the object as follows:


You can define methods for an object type by including a method definition in the object constructor function. You could define a function that would format and display the properties of the previously-defined objects; for example,

function displayCar() { var result = 'A Beautiful ' + this.year + ' ' + this.make + ' ' + this.model; pretty_print(result); }

where is a function to display a horizontal rule and a string. Notice the use of to refer to the object to which the method belongs.

You can make this function a method of by adding the statement

this.displayCar = displayCar;

to the object definition. So, the full definition of would now look like

function Car(make, model, year, owner) { this.make = make; this.model = model; this.year = year; this.owner = owner; this.displayCar = displayCar; }

Then you can call the method for each of the objects as follows:

car1.displayCar(); car2.displayCar();

Using for object references

JavaScript has a special keyword, , that you can use within a method to refer to the current object. For example, suppose you have a function called that validates an object's property, given the object and the high and low values:

function validate(obj, lowval, hival) { if ((obj.value < lowval) || (obj.value > hival)) { alert('Invalid Value!'); } }

Then, you could call in each form element's event handler, using to pass it the element, as in the following example:

<input type="text" name="age" size="3" onChange="validate(this, 18, 99)">

In general, refers to the calling object in a method.

When combined with the property, can refer to the current object's parent form. In the following example, the form contains a object and a button. When the user clicks the button, the value of the object is set to the form's name. The button's event handler uses to refer to the parent form, .

<form name="myForm"> <p><label>Form name:<input type="text" name="text1" value="Beluga"></label> <p><input name="button1" type="button" value="Show Form Name" onclick="this.form.text1.value = this.form.name"> </p> </form>

Defining getters and setters

A getter is a method that gets the value of a specific property. A setter is a method that sets the value of a specific property. You can define getters and setters on any predefined core object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

The following illustrates how getters and setters could work for a user-defined object .

var o = { a: 7, get b() { return this.a + 1; }, set c(x) { this.a = x / 2; } }; console.log(o.a); // 7 console.log(o.b); // 8 o.c = 50; console.log(o.a); // 25

The object's properties are:

  • — a number
  • — a getter that returns plus 1
  • — a setter that sets the value of to half of the value is being set to

Please note that function names of getters and setters defined in an object literal using "[gs]et property()" (as opposed to ) are not the names of the getters themselves, even though the syntax may mislead you to think otherwise. To name a function in a getter or setter using the "[gs]et property()" syntax, define an explicitly named function programmatically using (or the legacy fallback).

The following code illustrates how getters and setters can extend the prototype to add a property to all instances of the predefined class. It uses the class's existing and methods to support the property's getter and setter.

These statements define a getter and setter for the year property:

var d = Date.prototype; Object.defineProperty(d, 'year', { get: function() { return this.getFullYear(); },   set: function(y) { this.setFullYear(y); } });

These statements use the getter and setter in a object:

var now = new Date(); console.log(now.year); // 2000 now.year = 2001; // 987617605170 console.log(now); // Wed Apr 18 11:13:25 GMT-0700 (Pacific Daylight Time) 2001

In principle, getters and setters can be either

  • defined using object initializers, or
  • added later to any object at any time using a getter or setter adding method.

When defining getters and setters using object initializers all you need to do is to prefix a getter method with and a setter method with . Of course, the getter method must not expect a parameter, while the setter method expects exactly one parameter (the new value to set). For instance:

var o = { a: 7, get b() { return this.a + 1; }, set c(x) { this.a = x / 2; } };

Getters and setters can also be added to an object at any time after creation using the method. This method's first parameter is the object on which you want to define the getter or setter. The second parameter is an object whose property names are the getter or setter names, and whose property values are objects for defining the getter or setter functions. Here's an example that defines the same getter and setter used in the previous example:

var o = { a: 0 }; Object.defineProperties(o, {     'b': { get: function() { return this.a + 1; } },     'c': { set: function(x) { this.a = x / 2; } } }); o.c = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property console.log(o.b); // Runs the getter, which yields a + 1 or 6

Which of the two forms to choose depends on your programming style and task at hand. If you already go for the object initializer when defining a prototype you will probably most of the time choose the first form. This form is more compact and natural. However, if you need to add getters and setters later — because you did not write the prototype or particular object — then the second form is the only possible form. The second form probably best represents the dynamic nature of JavaScript — but it can make the code hard to read and understand.

Deleting properties

You can remove a non-inherited property by using the operator. The following code shows how to remove a property.

// Creates a new object, myobj, with two properties, a and b. var myobj = new Object; myobj.a = 5; myobj.b = 12; // Removes the a property, leaving myobj with only the b property. delete myobj.a; console.log ('a' in myobj); // yields "false"

You can also use to delete a global variable if the keyword was not used to declare the variable:

g = 17; delete g;

Comparing Objects

In JavaScript objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true.

// Two variables, two distinct objects with the same properties var fruit = {name: 'apple'}; var fruitbear = {name: 'apple'}; fruit == fruitbear; // return false fruit === fruitbear; // return false// Two variables, a single object var fruit = {name: 'apple'}; var fruitbear = fruit; // assign fruit object reference to fruitbear // here fruit and fruitbear are pointing to same object fruit == fruitbear; // return true fruit === fruitbear; // return true fruit.name = 'grape'; console.log(fruitbear); // yields { name: "grape" } instead of { name: "apple" }

For more information about comparison operators, see Comparison operators.

See also

Property Declaration in Objective C

Prior to declare properties features in Objective C, developers were expected to declare member variables and implement the getter and setter methods.

With advent of the declare properties and synthesize this effort is no more required. But for memory management concepts, its key to know how properties work in Objective C

A sample getter setter implementation

//KSCustomClass.h @interface KSCustomClass : NSObject { NSString *firstName; NSString *lastName; } -(NSString *)firstName; -(void)setFirstName:(NSString *)value; -(NSString *)lastName; -(void)setLastName:(NSString *)value;//KSCustomClass.m #import “KSCustomClass.h” @implementation KSCustomClass -(NSString *)firstName { return firstName; //or return [[firstName retain] autorelease]; } -(void)setFirstName:(NSString *)value { if (firstName != value) { [firstName release]; firstName = [value retain]; } }

With Declared Properties – the getter/setter methods would be synthesized or implemented automatically based on the attributes present in the @property directive.

The attributes help define the storage methodology and other behavior of the properties or member variables.

Attributes can be declared as

  • nonatomic or atomic (Mutually Exclusive)
  • readonly or readwrite (Mutually Exclusive)
  • retain or assign or copy or strong or weak (Mutually Exclusive)

Attribute Classification for Properties

Attributes are classifies based on

  • Writability 
  • Semantics 
    • strong
    • weak
    • retain
    • assign
    • copy
  • Atomicity


1. Writability
The readwrite and readonly specifies if the property has a setter method or not.


  • The readwrite attribute indicates if a property can be read and can be written into
  • If not specified, the default value is readwrite and both the getter and setter methods would be synthesized for the property


  • This attribute indicates that the property is read only and its value cannot be written into.
  • If the developer specifies readonly then only the getter method is synthesized automatically.
  • If a property is declared by attribute type as readonly and if we try to set its value using a direct assignment, we will get a compiler error

Sample Code:
@property (readonly) NSString *firstName;
@property (copy,readonly) NSString *firstName;
@property (retain,readonly) NSString *firstName;

2. Semantics

  • strong
  • weak
  • retain
  • assign
  • copy

The above attributes are Mutually exclusive i.e both copy and assign cannot be used on a property. Only one among these can be specified while declaring a property.


  • Gives ownership of the object to the class.
  • On using the retain attribute, the previous value is sent a release message and the new value is retained increasing the retain count by 1
  • Changes made to the object after it is retained will continue to reflect in the property
  • If a property is retained then it has to be released in the dealloc method

Sample Code:
@property (nonatomic, retain) NSString *firstName;
@synthesize firstName; //synthesize in the implementation

Alternative setter method if written without synthesize directive -(void)setFirstName:(NSString *)value { if (firstName != value) { [firstName release]; firstName = [value retain]; } }


  • Copy attribute gives ownership of the object to the class.
  • While calling the setter method a copy of the new value will be used and the older value will be released.

For e.g

  • If the property is a mutableArray and retain attribute is used for declaring the property, then post assignment any change to the mutableArray will continue to reflect in the new reference.
  • However if copy is used, then a copy of the NSMutableArray is created and any change in the original object will not reflect in the copied object.
  • Copy attribute increases the retain count of the object by 1
  • If a property is declared with copy attribute then it has to be released in the dealloc method

Sample Code:
If done using @property and @synthesize directive
@property (nonatomic, copy) NSString *firstName;
@synthesize firstName; //synthesize in the implementation

Alternative setter method if written without synthesize directive -(void)setFirstName:(NSString *)value { if (firstName != value) { [firstName release]; firstName = [value copy]; } }


  • Uses simple assign on the property.
  • The assign attribute is the default attribute. i.e if no semantics is specified
  • The assign attribute should be used for float, bool, int (i.e scalars or primitive data types).
  • Any property that declares a non-owning relationship should be declared using assign & copy or retain should not be used while declaring the property
  • Any property which is declared with assign attribute must be set to nil in the dealloc method.

Sample Code:
If done using @property and @synthesize directive
@property (nonatomic, assign) int objectCount;
//@property (nonatomic) int objectCount; // If not stated assign is used by default
@synthesize objectCount; //synthesize in the implementation

Strong or Weak

  • In an ARC environment where the keyword retain cannot be used while declaring a property, strong is used instead.The attribute “Strong” specifies a owning relationship of the destination object, this behavior is similar to retain.
  • Strong attribute can be used in both ARC and non-ARC environments.
  • Similarly Weak is used for declaring property that represents a non-owning kind of relationship. The behavior of weak attribute is similar to that of assign.

3. Atomicity

Atomic & Non Atomic

  • There is no keyword “Atomic” to declare a property.
  • It is understood and implicit that if an object is not nonatomic, it is atomic in nature and thus it is threadsafe. i.e only one thread can operate on the property at any point of time.
  • Atomic is the default behavior and if the desired functionality is to allow multiple threads to operate on the same property then nonatomic attribute has to be explicitly stated.
  • Having an atomic attribute would be equivalent to writing a synchronized block in the setter method to make it thread safe



Click to download the PDF Version of Knowledge Stack  – Cocoa_Declared_Properties


Posted in Cocoa, iOS, Objective C Tagged with: accessor methods, Cocoa, declared properties, memory management, Objective C, properties, property, synthesize

0 Thoughts to “Object C Property Assignments

Leave a comment

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *