1

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?

Dhanuka
  • 2,826
  • 5
  • 27
  • 38
  • No, this is a little different. – Alanas Macijauskas Jun 14 '15 at 14:39
  • `prototype` is not a keyword. `.prototype` is a simple property of the `constructorFunction`. – Bergi Jun 14 '15 at 15:32
  • `.prototype` works only with `new` operator. To set _real_ [[[prototype](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#Inheritance_with_the_prototype_chain)]] (internal link, \__proto__) without using `.prototype`, Use `Object.create( real_prototype )` or `Object.setPrototypeOf( existing_object, new_real_prototype)` – befzz Jun 14 '15 at 15:38

1 Answers1

2

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);
Ram
  • 143,282
  • 16
  • 168
  • 197