0

I'm trying to do something very simple. That is, create an object with a function I can call from somewhere else. I must be missing something. The code I'm trying right now is:

function Object1() {
    function function1() {
        alert("hello");
    }
}


Object1.function1();
1
  • 1
    Take a look at the answer I gave you, its actually just compiled from TypeScript. If you want to use object oriented programming, then I suggest that you use Typescript, since it will help you with most of the hassle. Commented Aug 23, 2013 at 6:04

7 Answers 7

2

The inner function is just a function implemented in the scope of the parent's one. It's not a member of the whole object.

Usually you do this:

function Object1() {
}

Object1.prototype = {
    function1: function () { 
         alert("hello");
    }
};

var obj = new Object1();
obj.function1();

It's important to note that this is using the prototype of the constructor function Object1, thus this approach will allow object inheritance:

var Object2 = Object.create({ function2: function() { } }, Object1.prototype);

See more about object-oriented prototype-based programming on Mozilla Developer Network (MDN):

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

3 Comments

Function1 should be lowercase. Also, won't you support my close vote?
@JanDvorak I just re-wrote his own code into the right one..
@JanDvorak On my way... you're right ;)
2

i think you will like this

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

Object1.prototype.function1 = function(prefix) {
  console.log(prefix + " " + this.name);
};


var obj = new Object1("naomi");
obj.function1("hello");
//=> "hello naomi"

An added demonstration for private data members

Object1.prototype.otherFunction = function() {

  // private variable
  var count = 0;

  // private function
  var incrementCounter = function() {
    count += 1;
  };

  return incrementCounter();
};

obj.otherFunction(); //=> 1
obj.otherFunction(); //=> 2
obj.otherFunction(); //=> 3

Just for fun, here's a subclass, too!

var Object2 = function(name, numberOfCats) {

  // call parent constructor
  Object1.call(this, name);

  this.numberOfCats = numberOfCats;
};

// setup prototype chain
Object2.prototype = Object.create(Object1.prototype, {constructor: {value: Object2}});

// an object2 public instance method
Object2.prototype.sayHello = function() {
  console.log(this.name + " has " + this.numberOfCats + " cats");
};

Usage is as you'd expect

var obj2 = new Object2("naomi", 3);
obj2.sayHello()
//=> "naomi has 3 cats"

Our method from Object1 is inherited too

obj2.function1("hi my name is");
//=> "hi my name is naomi"

And the private one too

obj2.otherFunction(); //=> 1
obj2.otherFunction(); //=> 2

8 Comments

Isn't this my exact answer, is it? :D
@MatíasFidemraizer it comes pretty close :-) But I'd give the benefit of doubt and not downvote for stealing what can be explained by not having noticed.
@MatíasFidemraizer, nope. You're using named functions for the Object1 definition and an object literal for the prototype. Not my style and certainly not my recommendation.
@naomik I'm torn as to which style to prefer... but if you assign a brand new prototype, be sure to set the constructor properly.
@JanDvorak can you elaborate on that?
|
2

This function would be 'private'.

To make it publicly accessible, you would need to do something like this:

function Object1() 
{
    this.Function1 = function() 
    {
        alert("hello");
    }
}

var thingy = new Object1();
thingy.Function1();

Similarly, to make private variables, you would use:

function Object1()
{
    var myPrivateVariable = 'something';
}

While public variables would be:

function Object1()
{
    this.myPublicVariable = 'something';
}

Try to avoid declaring a bunch of your variables as global, which happens by accident when you forget to declare them directly:

function Object1()
{
    globalVariable = 'oops';
}

JavaScript handles OOP quite a bit differently than most other languages, especially when it comes to prototyping and closures.

THIS is a decent link to the basics, but I also recommend the classic "JavaScript: The Good Parts" as well.

3 Comments

The first example isn't working for me. jsfiddle.net/RyvCn
My bad... I was sloppy. I just edited his original code to make the function public; but you are both correct... the object needs to be instantiated before it can be used.
Edited post to make that clearer.
2

I believe this is the best way to achieve what you want.

var Thing = (function () {
    function Thing(varOne) {
        this.varOne = varOne;
    }
    Thing.prototype.saySomething = function () {
        console.log(this.varOne);
    };
    return Thing;
})();

var app = new Thing("Cheese");
app.saySomething();

If you want to use objects and classes inside JavaScript, might I take the liberty to suggest TypeScript? It compiles into plain old javascript and can work with your existing javascript code.

Now some might suggest that this is a radical change. Its really not. Its just JavaScript with classes, and since its a superset of Javascript, it can make things infinitely easier. Furthermore, Typescript will be fully functional javascript when ECMAScript 6 is released, so why not use the to-be-released features today, and when it does come out, you can just change the type extension from typescript to javascript. If you just want to take a look at how it works, just look here.

Demo:

This is from a nodejs console.

> var Thing = (function () {
...     function Thing(varOne) {
.....         this.varOne = varOne;
.....     }
...     Thing.prototype.saySomething = function () {
.....         console.log(this.varOne);
.....     };
...     return Thing;
... })();
undefined
> var app = new Thing("Cheese Cake");
undefined
> app.saySomething();
Cheese Cake
undefined
>

I generated the above js code using Typescript, this is what the Typescript looks like:

class Thing {
    constructor( public varOne: string) {}

    saySomething (): void {
        console.log(this.varOne);
    }
}

var app = new Thing("Cheese");
app.saySomething();

As you can see, the syntax is much cleaner. You can go to Typescript's official website to learn more.

24 Comments

Nice, but why not inline the IIFE? There's nothing which scope to contain.
@JanDvorak: Just changed the code.
Nice, but I still don't see the need for the IIFE
Also, if you're going to suggest a brand new language, perhaps you should at least say why the user should make such a radical change (even if valid javascript is mostly valid typescript)
@JanDvorak: Why, what rule am I breaking?
|
1

You can do this:

Class1 = function () {
    this.Function1 = function() {
        alert("hello");
    }
}

var Object1 = new Class1()
Object1.Function1();

1 Comment

Function1 should be lowercase. Also, won't you support my close vote?
0

I think this is what you want.

var Object1 = {
    Function1: function() {
        alert("hello");
    }
}

Object1.Function1();

2 Comments

Function1 should be lowercase. Also, won't you support my close vote?
@JanDvorak I already have. Vote count is 2 now :)
0

As you said that you want to create an object and an function inside that object, this is how it should be done:-

var myFunc = function() {   
    alert("Hello");
}

var myObj  = {"func":myFunc};

Now you can use:- myFunc.func();

2 Comments

this isn't very object oriented, however
I think that that "should" should go away.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.