G Naga Subrahmanyam G Naga Subrahmanyam - 1 month ago 8
Javascript Question

How to call JavaScript object methods in one statement (Method Chaining)

I made an object inside function. I want to call object methods in one
statement.



(function(){
s4 = function(getSection){
var self = {
name: function(getname){
console.log("Name of the Student " +getname);
},

subject: function(getsub){
console.log(" & Studying " +getsub);
}

}
return self;
}
})();

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Details</title>
</head>
<body>
<div class="hello">
<h1>Student Details</h1>
</div>
<script src="script.js"></script>
<script>
s4("5th").name("John"); //This works fine
s4("5th").subject("Python"); //This works fine
s4("5th").name("John").subject("Python"); //Shows error: SCRIPT5007: Unable to get property 'subject' of undefined or null reference


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





When I call
s4("5th").name("John").subject("Python");

Shows error:


SCRIPT5007: Unable to get property 'subject' of undefined or null reference


Please help me solve this issue.
Thanks in advance.

Answer

In your methods, return the object. return this in name and subject. This is called method chaining and it works by returning an object.

(function() {
  s4 = function(getSection) {
    var self = {
      name: function(getname) {
        console.log("Name of the Student " + getname);
        return this;
      },
      subject: function(getsub) {
        console.log(" & Studying " + getsub);
        return this;
      }
    }
    return self;
  }
})();

s4("5th").name("John");
s4("5th").subject("Python");
s4("5th").name("John").subject("Python");