What makes the object.prototype to the constructor function if he has no name?

83 Views Asked by At

My following code is this:

 var triangle = {a:1, b:2, c:3};

function constructorFunction() {
  this.color = "red";
}

constructorFunction.prototype = triangle;

I know that the prototype keyword extends classes in this syntax: Object.prototype.method = function() {} But what for is this example? after constructorFunction.prototype there is no property or method name, what happens here?

1

There are 1 best solutions below

4
On BEST ANSWER

after constructorFunction.prototype there is no propertie or method name

That's not true. The prototype of the constructor is set using triangle object. The prototype has 3 properties.

prototype is an object. Consider these examples:

var obj = { 'baz': 'bar' };
obj = {
   'foo': 'bash'
}
// obj => { 'foo': 'bash' }

In the above snippet the obj variable's value is reset using an object literal.

var obj = { 'baz': 'bar' };
obj.foo = 'bash';

// obj => { 'baz': 'bar', 'foo': 'bash' }

In the above example the original object is extended by using dot notation.

i try console.log(constructorFunction.a); but it returns undefined.

That's because you haven't created an instance. The a is property of the constructor's prototype object.

console.log(constructorFunction.prototype.a);

If you create an instance object then a is a property of that instance.

var ins = new constructorFunction();
console.log(ins.a);