Creating Custom JavaScript objects #3
EasyProgramming.net tutorial on creating dynamic objects using the 'new' keyword
by Nazmus Nasir
HTML
<!-- JavaScript Objects - Creating Custom JavaScript objects #39 -->
<p>
Welcome to the 39th Easy JavaScript tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. Let's continue to look at JavaScript objects by creating our own custom objects using the <code>new</code> keyword. Let's also utilize the <code>this</code> keyword.
</p>
<p>
You can create an object template (also known as a constructor) which will act as a placeholder for new objects. You can then create
</p>
<h2>
Syntax of an object constructor:</h2>
<p>
<code><pre>
var person = function(param1, param1, param3){
this.name1 = param1,
this.name2 = param2,
this.name3 = param3,
method1 = function(){
//write what method1 does
}
};
</pre>
</code>
</p>
<h2>
Creating and accessing new object:
</h2>
<code>
<pre>var item1 = new person(arg1, arg2, arg3);</pre>
<pre>var item2 = new person(arg1, arg2, arg3);</pre>
<pre>item1.name1</pre>
</code>
<p>
<h2>
Let's practice:</h2>
<span id="output">___</span>
<br /><br />
JavaScript
var phone = function(brand, model, os, colorF, colorB){
this.brand = brand,
this.model = model,
this.os = os,
this.color = {
front : colorF,
back : colorB
},
makeCall = function(){
//does something
}
}
var x = new phone('Samsung','S7','Android','black','white');
var y = new phone('Apple','iPhone','iOS','White','white');
var z = new phone('Apple','iPhone','iOS','White','white');
var a = new phone('Apple','iPhone','iOS','White','white');
var b = new phone('Apple','iPhone','iOS','White','white');
console.log(x.color.back);
console.log(y.brand + ' ' + y.model);
console.log(b.brand);