//1.对象冒充 function ClassA(sColor) { this.color = sColor; this.sayColor = function() { alert(this.color); }; } function ClassB(sColor) { this.newMethod = ClassA; this.newMethod(sColor); delete this.newMethod; } var objA = new ClassA("red"); var objB = new ClassB("blue"); objA.sayColor(); objB.sayColor(); // 2.Call()方法 function ClassA(sColor) { this.color = sColor; this.sayColor = function() { alert(this.color); }; } function ClassB(sColor) { ClassA.call(this, sColor); } var objB = new ClassB("yellow"); var objA = new ClassA("red"); objA.sayColor(); objB.sayColor(); // 3. apply()方法 function ClassA(sColor) { this.color = sColor; this.sayColor = function() { alert(this.color); }; } function ClassB(sColor) { ClassA.apply(this, arguments); } var objB = new ClassB("black"); objB.sayColor(); // 4. 原型链 function ClassA() { } ClassA.prototype.color = "red"; ClassA.prototype.sayColor = function() { alert(this.color); }; function ClassB() { } ClassB.prototype = new ClassA(); var objA = new ClassA(); var objB = new ClassB(); objB.color = "green"; objB.sayColor();
时间: 2024-10-14 19:19:38