DEV Community

Mahin Tazuar
Mahin Tazuar

Posted on

Javadcript Prototype Property

Image descriptionPrototype is like some kind of inheritance concept but it's totally different from other languages. Mainly it comes for this purpose, when we are creating an object using by function constructor, we can not change property outside from that. But we can modify this functions constructor using the prototype. The condition is every time must be needed to use a new keyword.Prototype mainly works when we need to use extra object method or any object property then prototype gives access with a specific object or something where we need to get access. But you think you can add an extra method or property using '.'.Like

 let x = {};
x.play = function(){
//console.log('using method')
};
Enter fullscreen mode Exit fullscreen mode

In here have a condition, you can create this method but if you want using this same method another function or object creator or etc. You need to define the code again and again. So if we are using the prototype, we can call a method or property top of the code and we can use that where we want, In this process, we do not need to write code again and again.
Remember that function creates an object using by constructor though it's working behind the scene.

let x= {  name:"mahin"} // x.__proto__
let y = [12,2,4]  // y.__proto__
function func(){ } // func.prototype
Enter fullscreen mode Exit fullscreen mode

When we are initialization a function, array, object. Every time javascript is added by default some hidden property. which one is a prototype or proto. prototype only working with function. Other time working proto. Those are the same things.

let ss = {
    say:function(x){
        this.adress = x;
        return this;
    }
}
function Person(first) {
  this.firstName = first;
}
Person.prototype = ss;
const myFather = new Person("John");
console.log(myFather.say('dhajka'));
// its different for __proto__
let ss = {
    say:function(x){
        this.adress = x;
        return this;
    }
}
let Person = {
    names:'mahin'
}
Person.__proto__ = ss;
const myFather = Person;
console.log(myFather.say('mahin'));


Enter fullscreen mode Exit fullscreen mode

Remember we need to use this keyword for creating an object. actually, this means an object and we know if we are want to create a new object we need to call the object. property. If you want to learn more you can explore Object.create.
sometimes, when we are completely using prototype then if we can console the object/function/array we can find a children prototype inside a parent prototype that's mean parent object data inside the first prototype and the last prototype is chield prototype.

Top comments (0)