JavaScript/Notes/Function: Difference between revisions

From Noisebridge
Jump to navigation Jump to search
No edit summary
Line 41: Line 41:
</source>
</source>
Hint, see: http://ecma-international.org/ecma-262/5.1/#sec-15.8.2.11
Hint, see: http://ecma-international.org/ecma-262/5.1/#sec-15.8.2.11
What does the following code do when run? Explain.
<source lang="javascript">
function Duck () {
  this.sound = "Quack!";
  this.speak = function() {
    alert(this.sound);
  };
};
function Goose(){
};
Goose.prototype = {
  sound : "Honk!"
};
new Duck().speak.call(new Goose);
</source>

Revision as of 17:44, 4 December 2013

Variable this

<source lang="javascript"> function Slider(dir) {

 this.dir = dir;

} Slider.prototype.move = function(d) {

 alert(this.dir + ", " + d);

}; var move = new Slider("h").move; move(1); // Explain the result. </source>

Assignment

Function.prototype.call

1) Convert a NodeList into an Array (Hint, see lesson 1 on Array Generics). <source lang="javascript"> var nodeList = document.body.childNodes; // your code here! var nodeArray; </source>

Function.prototype.apply

1) Write a `bind` function -- roll your own, or search MDN.

2) Using `apply`, ind the latest and earliest date value in an array of Dates and construct a new Date object, respectively. <source lang="javascript"> var mon = new Date("December 02, 2013") var tue = new Date("December 03, 2013") var wed = new Date("December 04, 2013") var thu = new Date("December 05, 2013") var fri = new Date("December 06, 2013") var sat = new Date("December 07, 2013") var sun = new Date("December 08, 2013")

var dates = [ thu, tue, mon, sun, fri, sat, wed ];

// your code here! var latest; var earliest; </source> Hint, see: http://ecma-international.org/ecma-262/5.1/#sec-15.8.2.11

What does the following code do when run? Explain. <source lang="javascript"> function Duck () {

 this.sound = "Quack!";
 this.speak = function() {
   alert(this.sound);
 };

};

function Goose(){ }; Goose.prototype = {

 sound : "Honk!"

};

new Duck().speak.call(new Goose); </source>