Create Custom Methods in JS
EasyProgramming.net tutorial on creating custom methods
by Nazmus Nasir
HTML
<!-- JavaScript Objects - Creating Custom JavaScript Methods #40 -->
<p>
Welcome to the 40th 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 methods within our custom objects.
</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,
this.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(name, price, brand, model, os, colorF, colorB){
this.name = name,
this.price = price,
this.brand = brand,
this.model = model,
this.os = os,
this.color = {
front : colorF,
back : colorB
},
this.belongsTo = function(){
return this.brand + ' ' + this.model + ' belongs to ' + this.name + ' and the os is ' + this.os;
},
this.totalPrice = function(tax){
return (this.price * tax ) + this.price;
}
}
var x = new phone('Naz',100,'Samsung','S7','Android','black','white');
var y = new phone('Barry', 200,'Apple','iPhone','iOS','White','white');
console.log(x.belongsTo() + " and it costs " + x.totalPrice(0.10));
console.log(y.belongsTo() + " and it costs " + y.totalPrice(0.10));