So if I was to create an object literal like this..
var person1 = {
age : 28,
name : 'Pete' }
Then I add a function to the object…
person1.sayHelloName = function(){
return 'Hello ' + this.name;
};
alert(person1.sayHelloName());
Im wondering where the ‘prototype’ keyword comes into all this. I cant add a prototype to an object (only to a function constructor) so would I be able/have to use the prototype in this scenario.
You can’t use the
prototypein this way because, like you say, it’s used to add properties to a constructor which must be defined with thefunction()keyword. What you are doing in your example is extending theperson1object, but that object is just a single variable and not an instantiable class. Meaning you can’t “create” anotherperson1using thenewkeyword, whereas you could if it were an instance of a defined class.