Skip to content

Instantly share code, notes, and snippets.

@tarekahsan709
Last active October 10, 2017 04:45
Show Gist options
  • Save tarekahsan709/ed7dfa199155c8f76a55cc31a8015b52 to your computer and use it in GitHub Desktop.
Save tarekahsan709/ed7dfa199155c8f76a55cc31a8015b52 to your computer and use it in GitHub Desktop.

We can create object in javascript using constructor. By conention constructor name should be in uppercase. The created object will get all the define property as well as a hidden property called prototype. Which is also a object and it's value either null or object. The constructor will have its this variable bound to a newly created fresh object.

function Student (name, id) {
  this.name = name;
  this.id = id;
  this.details = function (){
    return "Name of the object " + this.name + " and it's id " + this.id;
  }
}
var objOne = new Student("jimmy", "006");
var objTwo = new Student("Tarek", "007");

By default all the created object had a property called prototype which hold an empty object. We can add new property or method and it will add in prototype.

function Student (name, id) {
	this.name = name;
  this.id = id;
  this.details = function (){
  	return "Name of the object " + this.name + " and it's id " + this.id;
  }
}
Student.prototype.newProperty = "Added new property";
var objOne = new Student("jimmy", "006");
var objTwo = new Student("Tarek", "007");
console.log(objOne.newProperty);
console.log(objTwo.newProperty);

we can use Object.create to create an object with a specific prototype.

//Custom Prototype
var protoRabbit = {
	speak: function (line){
  	console.log(this.name + ' and ' + line);
  }
};

var rabbit = Object.create(protoRabbit);
rabbit.name = "jabed";
rabbit.speak("Hello Moyna");
rabbit.name = "sajal";
rabbit.speak("Hello Master X");

All properties that we create by simply assigning to them are enumerable. The standard properties in Object.prototype are all nonenumerable, which is why they do not show up in such a for/in loop.

It is possible to define our own nonenumerable properties by using the Object.defineProperty function, which allows us to control the type of property we are creating.

Object.defineProperty(Object.prototype, "hiddenNonsense",
                      {enumerable: false, value: "hi"});

We can create object without prototype

var student = Object.create(null);
console.log(student);

Here's an empty object with prototype

var Student = new Object();
console.log(Student);

We cann add property to this object

myCar.make = 'Ford';
myCar.model = 'Mustang';
myCar.year = 1969;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment