Search

12/28/2008

call - MDC

call - MDC
You can use call to chain constructors for an object, similar to Java. In the following example, the constructor for the product object is defined with two parameters, name and value. Another object, prod_dept, initializes its unique variable (dept) and calls the constructor for product in its constructor to initialize the other variables.


function product(name, value){
this.name = name;
if(value >= 1000)
this.value = 999;
else
this.value = value;
}

function prod_dept(name, value, dept){
this.dept = dept;
product.call(this, name, value);
}

prod_dept.prototype = new product();

// since 5 is less than 1000, value is set
cheese = new prod_dept("feta", 5, "food");

// since 5000 is above 1000, value will be 999
car = new prod_dept("honda", 5000, "auto");

沒有留言: