Hello PHP developer, please meet the JavaScript object. It’s your friend :-) Actually JavaScript has similar capabilities when it comes to object oriented programming, and mastering the JavaScript object is your first step on the way to program great code in JavaScript.
In the following example you will see a simple JavaScript object with the following features:
- Constructor method
- Defining an object property
- Getter and setter functions for object property
- How to instantiate and use the object
Example Object Code
var MyObject = function() { this.foo = 'bar'; this.construct = function() { // Do you construction stuff here } this.setFoo(value) { this.foo = value; } this.getFoo() { return this.foo; } this.construct(); }
Example Object Usage
var test = new MyObject; test.setFoo('New Value'); alert(test.getFoo());
Use console instead of alert
console.log(test.getFoo());
Using the console log method allows you to write variables into the concole, where you can easily debug them with your browser. This is a much more convenient debug workflow than using alerts.
No comments yet (leave a comment)