CS174
Chris Pollett
Apr 21, 2021
var myArr = new Array(1, 2, "hello") var myArr = new Array(100); var myArr = [1,2,3]; //to access myArr[0] //to determine length myArr.length
var names = new Array("Mary", "Murray", "Max"); var nstring = names.join(":");
var a = [1, 2, 3]; a.concat(4, 5);
(//we'll talk more about functions in a moment) function my_callback(item, index) { alert(index + ":" + item); } var a = [1, 2, 3]; a.forEach(my_callback);
function swap(i, j, a) { var tmp=a[i]; /* explicitly defined variables have scope within the function if I had declared the variable implicitly it would have global scope */ a[i] = a[j]; a[j] = tmp; }
swap(10, 5, b);
var c = swap;So could call:
c(10, 5, b);
function swap() { var i = arguments[0], j=arguments[1], a=arguments[2]; //same code as before }
swap = function(i, j, a) { /* same code as before*/ }
function car(new_make, new_model, new_year) { this.make = new_make; this.model = new_model; this.year = new_year; }
my_car = new car("Ford", "Contour SVT", "2000");
function display_car() { document.write("Make:", this.make, "<br />"); document.write("Model:", this.model, "<br />"); document.write("Year:", this.year, "<br />"); } function car(new_make, new_model, new_year) { //same as before this.display = display_car; }
function car(new_make, new_model, new_year) { //same as before } car.prototype.display = display_car;
function car(new_make, new_model, new_year) { //same as before car.prototype.display = function() { document.write("Make:", this.make, "<br />"); document.write("Model:", this.model, "<br />"); document.write("Year:", this.year, "<br />"); } }
function A() { } A.prototype.foo = function() { alert("foo"); } function B() { } B.prototype = new A(); /* we just made B's prototype an instance of an A function object which has its own prototype. So property look up for B, looks within its instance, then within it prototype, which is an instance of A, to see if it is a property of A, then it looks at A's prototype to see if the property is there. As A's prototype is an Object, it finally looks at Object's prototype to see if the property is there. */ B.prototype.goo = function() { alert("goo"); } a = new A(); a.foo(); // alert with foo in it b = new B(); b.foo(); // alert with foo in it b.goo(); // alert with goo in it a.goo(); // type error goo is not a function of A