日期:2014-05-16 浏览次数:20308 次
var color = "red"; function sayColor(p) { alert(p + this.color); }; sayColor();//弹出undefinedred; var obj = new Object(); obj.color = "blue"; sayColor.call(obj, "color is ");//弹出color is blue //sayColor.apply(obj, ["color is "]);
function ClassA(c) { this.color = c; this.sayColor = function () { alert(this.color); }; } function ClassB(c, n) { ClassA.apply(this, arguments); this.name = n; this.sayName = function () { alert(this.name); }; } var objA = new ClassA("blue"); var objB = new ClassB("red", "John"); objA.sayColor(); //输出 "blue" objB.sayColor(); //输出 "red" objB.sayName(); //输出 "John"
function ClassA(c) { this.color = c; } ClassA.prototype.sayColor = function () { alert(this.color); }; function ClassB(c, n) { ClassA.call(this, c); this.name = n; } var objB = new ClassB("red", "cxy"); objB.sayColor(); //运行报错 不存在这个方法
function ClassA(c) { this.color = c; } ClassA.prototype.sayColor = function () { alert(this.color); }; function ClassB(c, n) { ClassA.call(this, c); this.name = n; } ClassB.prototype = new ClassA(); ClassB.prototype.sayName = function () { alert(this.name); }; var objA = new ClassA("blue"); var objB = new ClassB("red", "cxy"); objA.sayColor(); //输出 "blue" objB.sayColor(); //输出 "red" objB.sayName(); //输出 "cxy"