Joza100
Joza100

Reputation: 356

JavaScript object's function not returning

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!!

Upvotes: 2

Views: 2042

Answers (7)

tevemadar
tevemadar

Reputation: 13225

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.

Upvotes: 2

Gacci
Gacci

Reputation: 1398

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

Upvotes: 0

Daniel Taub
Daniel Taub

Reputation: 5379

<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

Upvotes: 0

Abhi Andhariya
Abhi Andhariya

Reputation: 560

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();

Upvotes: 0

CraigRodrigues
CraigRodrigues

Reputation: 86

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"

Upvotes: 1

Mihir Bhende
Mihir Bhende

Reputation: 9055

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;
  }

}

Upvotes: 0

Gabe Rogan
Gabe Rogan

Reputation: 3711

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());

Upvotes: 0

Related Questions