Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object properties and functions

In JavaScript I see a few different ways, certain tasks can be performed within an object for example, the object Egg I have below.

Can anyone tell me the difference between each one, why I would use one and not the other etc

 var Egg = function(){

    //Properties

    var shell = "cracked" // private property 

    this.shell = "cracked" // public property

    shell: "cracked" // what is this??

    //functions

    function cook(){

        //standard function
    }

    cook: function(){
        //what kind of function is this?
    }

    //not sure what this is

    details: {
        //What is this? an array :S it holds 2 elements?
        cost: 1.23,
        make: 'Happy Egg';
    }




}
like image 342
Ben_hawk Avatar asked Jul 19 '12 17:07

Ben_hawk


People also ask

What are the properties of object in JavaScript?

Object properties are defined as a simple association between name and value. All properties have a name and value is one of the attributes linked with the property, which defines the access granted to the property. Properties refer to the collection of values which are associated with the JavaScript object.

Can you put a function in an object JavaScript?

You can call a function inside an object by declaring the function as a property on the object and invoking it, e.g. obj. sum(2, 2) . An object's property can point to a function, just like it can point to a string, number or other values. Copied!

What is objects properties and methods in JavaScript?

Object MethodsMethods are actions that can be performed on objects. Object properties can be both primitive values, other objects, and functions. An object method is an object property containing a function definition. JavaScript objects are containers for named values, called properties and methods.

How many types of object properties are there in JavaScript?

Properties are identified using key values. A key value is either a String value or a Symbol value. There are two types of object properties: The data property and the accessor property.


3 Answers

Your code snippet isn't quite valid, but here are a few things it raises:

Property initializers, object initializers

You've asked what shell: cracked is. It's a property initializer. You find them in object initializers (aka "object literals"), which are written like this:

var obj = {
    propName: "propValue"
};

That's equivalent to:

var obj = {};
obj.propName = "propValue";

Both of the above create an object with a property called propName which has a string value "propValue". Note that this doesn't come into it.

Functions

There are a couple of places where functions typically come into it vis-a-vis objects:

Constructor functions

There are constructor functions, which are functions you call via the new operator. Here's an example:

// Constructor function
function Foo(name) {
    this.name = name;
}

// Usage
var f = new Foo("Fred");

Note the use of the keyword this in there. That's where you've seen that (most likely). When you call a constructor function via new, this refers to the new object created by the new operator.

this is a slippery concept in JavaScript (and completely different from this in C++, Java, or C#), I recommend these two (cough) posts on my blog:

  • You must remember this
  • Mythical methods

Builder/factory functions

You don't have to use constructor functions and new, another pattern uses "builder" or "factory" functions instead:

// A factory function
function fooFactory(name) {
    var rv = {}; // A new, blank object

    rv.name = name;

    return rv;
}

// Usage
var f = fooFactory("Fred");

Private properties

You mentioned "private" properties in your question. JavaScript doesn't have private properties at all (yet, they're on their way). But you see people simulate them, by defining functions they use on the object as closures over an execution context (typically a call to a constructor function or a factory function) which contains variables no one else can see, like this:

// Constructor function
function EverUpwards() {
    var counter = 0;

    this.increment = function() {
        return ++counter;
    };
}

// Usage:
var e = new EverUpwards();
console.log(e.increment()); // "1"
console.log(e.increment()); // "2"

(That example uses a constructor function, but you can do the same thing with a factory function.)

Note that even though the function we assign to increment can access counter, nothing else can. So counter is effectively a private property. This is because the function is a closure. More: Closures are not complicated

like image 89
T.J. Crowder Avatar answered Oct 23 '22 09:10

T.J. Crowder


Sure, Ben.

This sort of gets to the bottom of the dynamism of JavaScript. First, we'll look at basics -- if you're coming from a place where you understand class-based languages, like, say, Java or C++/C#, the one that is going to make the most sense is the constructor pattern which was included very early on:

function Egg (type, radius, height, weight) {
    // private properties (can also have private functions)
    var cost = (type === "ostrich") ? 2.05 * weight : 0.35 * weight;

    // public properties
    this.type = type;
    this.radius = radius;
    this.height = height;
    this.weight = weight;
    this.cracked = false;

    // this is a public function which has access to private variables of the instance
    this.getCost = function () { return cost; };
}

// this is a method which ALL eggs inherit, which can manipulate "this" properly
// but it has ***NO*** access to private properties of the instance
Egg.prototype.Crack = function () { this.cracked = true; };


var myEgg = new Egg("chicken", 2, 3, 500);

myEgg.cost; // undefined
myEgg.Crack();
myEgg.cracked; // true

That's fine, but sometimes there are easier ways of getting around things. Sometimes you really don't need a class.

What if you just wanted to use one egg, ever, because that's all your recipe called for?

var myEgg = {};  // equals a new object
myEgg.type = "ostrich";
myEgg.cost = "......";
myEgg.Crack = function () { this.cracked = true; };

That's great, but there's still a lot of repetition there.

var myEgg = {
    type : "ostrich",
    cost : "......",
    Crack : function () { this.cracked = true; }
};

Both of the two "myEgg" objects are exactly the same.

The problem here is that EVERY property and EVERY method of myEgg is 100% public to anybody.

The solution to that is immediately-invoking functions:

// have a quick look at the bottom of the function, and see that it calls itself
// with parens "()" as soon as it's defined
var myEgg = (function () {
    // we now have private properties again!
    var cost, type, weight, cracked, Crack, //.......

    // this will be returned to the outside var, "myEgg", as the PUBLIC interface
    myReturnObject = {
        type : type,
        weight : weight,
        Crack : Crack, // added benefit -- "cracked" is now private and tamper-proof
        // this is how JS can handle virtual-wallets, for example
        // just don't actually build a financial-institution around client-side code...
        GetSaleValue : function () { return (cracked) ? 0 : cost; }
    };

    return myReturnObject;
}());

myEgg.GetSaleValue(); // returns the value of private "cost"
myEgg.Crack();
myEgg.cracked // undefined ("cracked" is locked away as private)
myEgg.GetSaleValue(); // returns 0, because "cracked" is true

Hope that's a decent start.

like image 25
Norguard Avatar answered Oct 23 '22 09:10

Norguard


You are mixing syntaxes between object property declaration and simple javascript statements.

// declare an object named someObject with one property
var someObject = {
    key: value
};

// declare an anonymous function with some statements in it
// and assign that to a variable named "someFunction"
var someFunction = function () {
    // any javascript statements or expressions can go here
};
like image 35
jbabey Avatar answered Oct 23 '22 10:10

jbabey