Ben
Ben

Reputation: 1233

Assignment operator for functions

I'm having a bit of trouble understanding what the assignment operator is used for when dealing with methods, functions, etc. Here is the example in w3 school for defining an object

function person(firstname,lastname,age,eyecolor){
this.firstname=firstname;
this.eyecolor=eyecolor;

this.newlastname=newlastname;
}

and this is the actual function (place somewhere else)

function newlastname(new_lastname){
this.lastname=new_lastname;
}

It's just very weird to me throughout javascript, you say

object.methodname = somefunctionname

Any ideas to help me conceptualize it?

Upvotes: 2

Views: 125

Answers (3)

Christoph
Christoph

Reputation: 51261

This is the cool thing about javascript. Functions are first-class objects, this means unlike other non-functional programming languages, you can hand them as parameters to other functions, return them from function and (like in your example) attach them to objects like a normal property.

This enables programming paradigmas like the (for the web) so important asynchronous function calls (callbacks).

Upvotes: 1

lanzz
lanzz

Reputation: 43208

This language feature is called First-class functions. The Wikipedia article is pretty comprehensive.

Upvotes: 1

James Allardice
James Allardice

Reputation: 166071

The code in your question is effectively the same as this:

function person(firstname, lastname, age, eyecolor) {
    this.firstname = firstname;
    this.eyecolor = eyecolor;

    //anonymous function assigned to newlastname property
    this.newlastname = function(new_lastname) {
        this.lastname = new_lastname;
    };
}

person is a constructor function (you would call it with the new operator to create a new instance). Every instance of person has three properties, firstname, eyecolor and newlastname.

The newlastname property is a method since it's value is a function. When you call that method, the instance of person on which it is called will get a lastname property.

For example:

var me = new person("James", "Allardice", 22, "Brown");
me.lastname; //undefined
me.newlastname("Something");
me.lastname; //Something

This is possible because in JavaScript, functions are objects.

Upvotes: 2

Related Questions