I have a good background in OOP, mostly in C++ and Java. I want to use objects in JavaScript, including inheritance. The articles I've read on JS inheritance always talk about the prototypal inheritance model. When creating functions (methods) for JS objects, they are always declared after the object itself is declared, and in a format such as: Object.prototype.funcName = function() { }
. Yes, this works, but it also seems to work when declaring the function inside the object, like: this.funcName = function() { };
This is one of the articles I've read: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance.
I've tested my code both ways and they seem to work identically well. Can anybody tell me if I will encounter any problems down the road by declaring my functions inside my objects (like standard OOP), or will it bite me in the end?
Here's 'my' way:
function Person(name) {
this.name = name;
this.greeting = function() {
console.log('Hi! I\'m ' + this.name + ' from Person');
};
};
Here is the prototypal way:
function Person(name) {
this.name = name;
};
Person.prototype.greeting = function() {
console.log('Hi! I\'m ' + this.name + ' from Person.proto');
};
Creating the object and calling the greeting works either way:
var person = new Person("Cool Dood");
person.greeting();
Any insights as to whether or not 'my' way of declaring the functions inside the object declaration would cause me problems in the future?