1

I'm trying todo some OO in Javascript, and I'm coming from C++ and Ruby. I've managed to create one object, but nesting an object inside is being alittle bit of a pain.

function Model()
{
   //...
}

function Player(props)
{
   var props = {
      // ...
   }

   var model = new Model(props); // I've tried 'this.model = new Model() as well
}

var props = {
   // ...
}
var player = new Player(props);

Player gets created fine, but if I try and nest the object it fails. What am I doing wrong.

0

1 Answer 1

2

Example

You were close. There are much better ways of "seudo-extending" object in javascript. jQuery.extend is one possible way. You can write your own method that check properties as well. I think the biggest break down for you was overwriting props in the Player function.

  • With functions this is key
  • Functions are the only scope in JavaScript, so be careful with naming variables
  • It's important to understand the difference between the object literal var a = {} and functions var a = new Method();. However, it seems you have that down well.

Code

function Model(data)
{
   this.Name = data.Name;
   this.Other = data.Other;
}

function Player(props)
{
   var privateProps = {
       Name: 'testing'
   };
   privateProps.Other = props.Other;
   this.model = new Model(privateProps); // I've tried 'this.model = new Model() as well
}

var props = {
    Other: 'Other'
}
var player = new Player(props);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.