Tag Archives: javascript

4 ways to create javascript class

1st: Create a class with a function:
function Fruit(fruitname) {
    this.name = fruitname;
    this.color = “”;
    this.getInfo = function() {
  return “This fruit is an ” + this.color + ‘ ‘ + this.name;
 };
}

or put the method outside:
function Fruit(fruitname) {
    this.name = fruitname;
    this.color = “red”;
    this.getInfo = getInfo_fruit();
    };
}

function getInfo_fruit() {
    return “This fruit is a ” + this.color + ‘ ‘ + this.name;
};

Create an object with it and then use it:
var fruit = new Fruit(‘apple’);
fruit.color = “red”;
alert(fruit.getInfo());
2nd: Create a class or an object:
var fruit = new function() {
    this.name = “”;
    this.color = “”;
    this.getInfo = function () {
        return “This fruit is a ” + this.color + ‘ ‘ + this.name;
    };
}

use it:
fruit.name = “apple”;
fruit.color = “red”;
alert(fruit.getInfo());
3rd:
Create a class:
var fruit = {
    name: “”,
    color: “”,
    getInfo: function () {
        return “This fruit is a ” + this.color + ‘ ‘ + this.name;
    }
}

use it:
fruit.name = “apple”;
fruit.color = “red”;
alert(fruit.getInfo());

4th: It’s said that this way is better. It puts the method outside as the prototype. In this way, when an object is created, the mothed wouldn’t be built as an instance in the memory of the computer:
function Fruit(){
  this.info = “This is a red apple”;
}

fruit.prototype.getInfo = function (){
  alert(this.info) ;
}

use it:
var fruit = new Fruit();
alert(fruit.getInfo);