2

i have a question about JavaScript! I've been studying JavaScript for a few days, but it wasn't that hard cuz i alread have a lot of knowledge from Java. I have programmed for long time until now. I work with objects and i wanted to add a function to the object. But that funcion doesn't work properly... Code:

<!DOCTYPE html>

<html>

<head>
<script type="text/javascript">

    function person(name){
        this.name = name;
    }

    function printName(){
        return this.name;
    }

    var joza = new person("Josip");


</script>
</head>
<body>
<script type="text/javascript">
document.write(joza.printName());
</script>
</body>

</html>

So this code is supposed to use the object's function and print out it's name... But... all I get is just a blank webpage! Please help!! Thank you!!

7 Answers 7

2

You got some brutal answers, but the one with a lexical closure seems to be missing. So here you are:

function Person(name){
  this.printName=function(){
    console.log(name);
  };
}
test=new Person("John");
test.printName();

The thing is that JavaScript functions retain the environment where they were declared. So here the inner function can access local variables of the outer function, even when the outer function is not running any more. Actually it is similar to accessing final local variables from anonymous inner classes in Java, just these variables do not have to be final (so it would be perfectly possible to provide a setName method, which would alter the same name variable).

It is not very important/interesting for this particular use case, but this is a common way how you can get parameters into callback methods for example.

And the best part for confusion:

Your original code can be used too. JavaScript is not very picky about "this", you can invoke any method on any object:

function Person(name){
  this.name=name;
}
function printName(){
  console.log(this.name);
}
test=new Person("Jane");
printName.call(test);

Functions are objects, and they have a call method. Where the first argument sets this, and the rest are just passed as arguments for the method itself. For completeness: there is an apply method too, where the arguments for the function are passed as an array.

This is not very important here either, however a thing you should keep in mind is that this is not necessarily the object you expect. Yet again callback methods: if you use an object method as a callback, when the browser invokes it, this is usually the window object.

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

5 Comments

Thank you very much for that call function!! I wanted to do something like that but i didn't know about call() thanks!! :D
@Joza100 ehm, you are welcome, just keep in mind that extensive use of call is considered terrible style. While you may find some of these details useful, the classic solutions for this problem are really the this.name=name;this.printName=function(){...}; or the ones with prototype (like this.name=name; in the constructor and person.prototype.printName=function(){...}; separately)
OK! Thanks!! If only i knew something about prototypes... I'll have to learn them
@Joza100 w3schools.com/js/js_object_prototypes.asp is a good start. From the usability point of view you normally end up at very similar places. However what is happening is different: altering the prototype means you have a single copy of the function and it is used for all objects (both existing and future objects), while putting anonymous functions into the constructor results in creating separate functions for each object - that is how the approach with lexical closure works: every Person object will have a different 'printName', referring its own local variable called 'name'
Now i get it... that's cool! The only reason why I don't really understand things such as prototypes and functions in another function is because the first language i learned was Java and there's no such thing in Java. It's different
1

Ignoring the HTML for now here is your code:

function person(name){
  this.name = name;
}

function printName(){
  return this.name;
}

var joza = new person("Josip");
joza.printName() // Error

So what's going on above is that you are creating this person constructor function and then another function outside of it. Your joza object does not have the printName function on it.

The printName function is just a regular function that has its own context for this, which in this case is just the window.

When you call joza.printName you will find that printName doesn't exist on the joza object you just created.

Try this instead by adding your printName method to the actual returned person object:

function person(name){
  this.name = name;
  this.printName = function() {
    return this.name
  }
}

var joza = new person("Josip");
joza.printName() // "Josip"

1 Comment

thanks for your answer but there is this same answer already! thanks for the explanation anways i'll mark this answer as correct now because of the explanation
0

Just a minor change (you're trying to call the printName method of the person object).

function person(name){
  this.name = name;
  this.printName = function() {
    return this.name;
  }
}

var joza = new person("Josip");

document.write(joza.printName());

3 Comments

Oh just noticed, that you wrote the same as me fiew seconds before me. i'll remove my answer.
Thank you very much. I followed TheNewBoston's tutorials and he wrote the function out of the first function and i just followed him. But, now i know what i wanted. Thank you
No problem. TheNewBoston is a great teacher! But sometimes he purposely leaves something out or doesn't follow best practice (to get his point across).
0

check this revision :

var person = function(name){

    var tmp = {};
    tmp.name = name;

    tmp.printName = function(){
        return tmp.name;
    }
return tmp;
}

var joza = new person("Josip");

Fiddle : https://jsfiddle.net/jwvvkgaf/

This is a factory pattern, one of the way to accomplish what you want.

If you want simple constructor pattern :

var person = function(name){
  this.name = name;

  this.printName = function() {
    return this.name;
  }

}

1 Comment

hmm.. i'm just a beginner in this programming language so this code is kinda hard to understand for me... i found a better answer! thanks for trying to help!! :D
0

Here's the way to add object like java in javascript

 function person(name){
            this.name = name;
        }

Add methods like this. All Person objects will be able to invoke this

person.prototype.printName = function(){
    return this.name;
}

Instantiate new objects with 'new'

var joza = new person("Josip");

Invoke methods like this

 joza.printName();

Comments

0
<html>
<head>
    <script type="text/javascript">
        function person(name) {
            this.name = name;

            this.printName = function() {
                return this.name;
            }
        }
        var joza = new person("Josip");

    </script>
</head>
<body>
    <script type="text/javascript">
        document.write(joza.printName());

    </script>
</body>
</html>

The

function printName(){
        return this.name;
    }

is not a member of Person ,so you can get the name property from it, you should put the method inside the pesron object

Comments

0

(function(global){
    function person(name){
        this.name = name;
    }

    person.prototype ={
      printName: function(){
        return this.name;
      },
    };
    
    window.person = person;
}(window));
    
var joza = new person("Josip");

document.write(joza.printName());

Let me break it down for you. (function(){ /* code in here */ }()) this is a scope. Basically kind of like a namespace so you don't pollute the window global variable. Then you declare the function person which is more or less your "constructor" that constructor initializes the property name. Then, put your functions inside the prototype and call them.

2 Comments

hmm.. i'm just a beginner in this programming language so this code is kinda hard to understand for me... i found a better answer! thanks for trying to help!! :D
Tried to explain it a little better, hope it helps!

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.