0

Hello guys i'm trying objects in javascript/node.js, actually i'm having a hard time on objects with functions inside them. This is my sample code whish the output should be:

Rohan says: Hello World

Here is my func.js

var myObject = function(name) {
    console.log(this.name + ' says: ');
    this.talk = function(msg) {
        console.log(msg);
        }
};

var phil = function (name) {
    this.name = name;
};

phil.prototype = new myObject();
var man = new phil('Rohan');
man.talk('Hello World');

I hope you can help me solve this problem in my code. Thanks guys.

Joenel de Asis
  • 364
  • 1
  • 12
  • 17
  • Your `myobject` function has an unused `name` parameter, and uses a (not initialized) `name` property. What do you want? Which of the two "classes" should be responsible for the name? In my answer it works, but is still confusing. – Bergi Sep 19 '13 at 03:22

3 Answers3

2

See Correct javascript inheritance. Don't use the new keyword for creating the prototype (you don't want to initialize it like an instance). Initialise the instance by applying the parent constructor. And for naming conventions: uppercase constructors would be nice.

function MyObject() {
    console.log(this.name + ' got created');
}
MyObject.prototype.talk = function(msg) {
    console.log("and says "+msg);
};

function Phil(name) {
    this.name = name;
    MyObject.call(this);
}
Phil.prototype = Object.create(MyObject.prototype);

var man = new Phil('Rohan');
man.talk('Hello World');
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

Modify your talk function to

this.talk = function (msg) {
    console.log(this.name + ' says: ' + msg);
}
Huy Le
  • 657
  • 5
  • 17
1
var myObject = function(name) {
    this.talk = function(msg) {
        console.log(msg);
    },
    this.setName = function(name) {
        this.name = name;
        console.log(name + ' says: ');
    }
};

var phil = function (name) {
    this.setName(name);
};

phil.prototype = new myObject();
var man = new phil('Rohan');
man.talk('Hello World');
Popsyjunior
  • 185
  • 10
  • This is what i'm saying. This Code. :) Thanks Popsyjunior. – Joenel de Asis Sep 19 '13 at 03:39
  • Try to call `man.talk('Hello world')` once again – Huy Le Sep 19 '13 at 03:43
  • [Do not use `phil.prototype = new myObject();`](http://stackoverflow.com/questions/12592913/what-is-the-reason-to-use-the-new-keyword-here) – Bergi Sep 19 '13 at 03:50
  • You're welcome. I'll like to believe that it's a homework or something you're trying out. @Bergi is right In real life applications, you'll want to use standard javascript inheritance. – Popsyjunior Sep 19 '13 at 07:43