0

I have Googled and also checked Stack Overflow answers for this. But I am not able to understand clearly on this. Can anyone help explain simply the following example please?

function myObject(){
    this.iAm = 'an object';
    myObject.prototype.values = "value";
    this.whatAmI = function(){
        alert('I am ' + this.iAm);
    }
}
var myObject1 = new myObject();
myObject1.values = "value2";
myObject1.iAm = "New";

alert(myObject1.values);


var myObject2 = new myObject();
alert(myObject1.values);

In the above code if I use this.iAm, it behaves in the same way prototype behaves.

I am new to Javascript Object Oriented Programming.

I expect many down votes. But I'm not concerned with that, because I just want to receive an explanation in a clear and simple way, that I have been able to find yet.

Kevin Welker
  • 7,719
  • 1
  • 40
  • 56
Vinoth Babu
  • 6,724
  • 10
  • 36
  • 55

1 Answers1

1

I'm going to try to guess/address your actual concerns.

See the following code snippet:

function A() {
   this.text = "hello";
}

var a = new A();
a.text = "hello world";

Actually there's only a difference between setting text property inside the constructor (i.e. this.text) function or once the object has been already created (i.e. a.text). Basically, this within the constructor function is the object being created and a variable is the object already created.

The only difference between the two is that a property defined in the object being created during the call to the constructor function will be created to all objects creared by the whole constructor function.

Now see the following code snippet too:

function A() {}
A.prototype = {
    text: "hello"
};

var a1 = new A();
var a2 = new A();

// both will output "hello"
console.log(a1.text);
console.log(a2.text);

A.prototype.value = "bye";

// both will output "bye"
console.log(a1.text);
console.log(a2.text);

Conclusion: properties defined in the prototype of a constructor function are shared by all objects sharing the same prototype. Thus, they're alive even if you create objects using the constructor function or not.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206