Various styles were used to implement chaining and my ultimate goal was to make the chains without using the new key word to form an object.
I have noticed something since that original post.
Here's that original post.
easy explanation of method chaining
Here are two code sets from that post.
Code set one:
<html>
<body>
<script type="text/javascript">
var toys = function(s) { this.toy = s; return this; };
var retoys = function(){ return "Cat: " + this.name + ", plays " + this.toy};
function cat(name) {
return {
name : name, toy : 'none',
plays : toys, //toys = function
toString : retoys, //retoys = function
};
}
var spotted_cat = cat("spotted").plays("bites yarn");
var striped_cat = cat("striped").plays("bites yarn");
document.write("<p>" + spotted_cat + "</p>");
document.write("<p>" + striped_cat + "</p>");
</script>
</body>
</html>
Code set two:
<html>
<body>
<script type="text/javascript">
function cat(name) {
function toys(s) { this.toy = s; return this; };
function retoys() { return "Cat: " + this.name + ", plays " + this.toy};
return {
name : name, toy : 'none',
plays : toys,
toString : retoys,
};
}
var spotted_cat = cat("spotted").plays("bites yarn");
var striped_cat = cat("striped").plays("bites yarn");
document.write("<p>" + spotted_cat + "</p>");
document.write("<p>" + striped_cat + "</p>");
</script>
</body>
</html>
Now here is a new implementation using no 'this' operator, no toString method, and no extra function for converting and combining the string.
<!DOCTYPE html>
<head>
<title>js object</title>
</head>
<body>
<script type="text/javascript">
var toyBox = function(player){
var toy = function(toyGet){
return "The " + player + " plays with the " + toyGet + "<br>";
}
return {
toy : toy
};
}
document.write(toyBox("Boy").toy("Ball"));
document.write(toyBox("Girl").toy("Doll"));
</script>
</body>
</html>
As you can see the toy function is referencing the 'player' parameter of toyBox. The chain comes out of the return of the literal and uses what parameters are provided.
I can't remember exactly what it was about the 'this' operator and what benefit it had for making method chains.
There is a discrepancy here between using the 'this' and just a plain return.
While using 'this' a toString is needed to convert the string for output, and the code needs extra object literal members to complete the operation.
I am wondering if there is some sort of benefit while using 'this' to produce method chaining versus benefits of just returning the function pointer in the literal.
The main benefit of either style is that the return is only applicable for the methods called in the chain. So it's nice to have for a quick extension directly in the object.
Is it easy vs. hard or is there a real reason for using 'this' to attach the properties to the function to accomplish method chaining?
This post has been edited by hiddenghost: 26 February 2012 - 06:23 PM

New Topic/Question
Reply



MultiQuote




|