Friday, 10 November 2017

General Information about Method and Property attributes in JS using OOP

Properties are variables contained in the class.In every instance of the object has those properties. Properties are set in the constructor of the class so that they are created on each instance.

Example: Code Snippet for Method and Property Attibute
//Example for Method attibute
<script type="text/javascript">
var Person = function (firstName) {
this.firstName = firstName;
console.log('Person instantiated');
};
var person1 = new Person('Allen boult');
var person2 = new Person('Chris Jordan');

// Show the firstName properties of the objects
console.log('person1 is ' + person1.firstName); // logs "person1 is Allen boult".
console.log('person2 is ' + person2.firstName); // logs "person2 is Chris Jordan".
//Example for Property attibute
//Define the class Car
function Car(speed) {
alert("Class CAR is Instantiated");
this.speed = speed;
}
Car.prototype.speed= 'Car Speed';
Car.prototype.setSpeed = function(speed) {
this.speed = speed;
alert("Gradually Car speed changed");
}

var car1 = new Car(40);
var car2 = new Car(70);

car1.setSpeed(130);
car2.setSpeed(140);

</script>

E.g. Description

The Property (Object attribute):
Properties are variables contained in the class. In every instance of the object has those properties. Properties are set in the constructor of the class so that they are created on each instance.
The keyword this refers to the current object, lets you work with properties from within the class. Accessing a property outside of the class is done with the syntax: InstanceName.Property, just like in C++, Java, and several other programming languages.
From the above example mentioned we define the firstNameproperty for the Person class at Instantiation in which we use the variables of person1 and person2.output displayed on the screen as follows
"person1 is Allen Bolt".
"person2 is Chris Jordan".
Methods:
Methods are same as function and they are defined like functions. To define a method, assign a function to a named property of the class's prototype property. Later, you can call the method on the object by the same name as you assigned the function to.
To define methods in a Class, all you have to do is just define an attribute and assign a function to it.From the above example mentioned we defined a method setSpeed() for the class Car. When the speed is changed compare to car1 it alerts the message as "Gradually Car Speed Changed".

READMORE

No comments:

Post a Comment