2

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?

0

3 Answers 3

2

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.

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

2 Comments

properties are methods...? I'm so mind blown right now. Properties can have functions as values...what is this madness!!! (coming from c++/c#/objective-c)
Yeah, I think that's a common reaction from developers more used to C/C++! The article lanzz linked to should help explain the general concept in more detail.
1

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

Comments

1

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).

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.