日期:2014-05-16  浏览次数:20337 次

JavaScript学习笔记_函数对象之间继承

因工作需要需要学习JavaScript 参考书主要为《JavaScript语言精粹》以及《JavaScript权威指南》现来总结学习经验。

关于对象继承的一个问题.

父类Fruit

//水果對象 有這幾個屬性name,color,weight,shape
//提供了對應的set 和 get方法,只對子類提供方法,不提供相應的屬性接口,
function Fruit(){
??????? //console.log(this);
?this.color = this.color||'';
?this.name = this.name||"fruit";
?this.weight =? this.weight||0 + '千克';
??????? this.shape = this.shape||'';
?this.set_name = function(name){
??this.name=name;
?};
?this.get_name = function(){
?
??return this.name;
?};
?this.set_color = function(color){
??this.color=color;
?};
?this.get_color = function (){
?
??return this.color;
?};
?this.set_shape = function(shape){
??this.shape = shape;
?};
?this.get_shape = function(){
??return this.shape;
?};
?this.get_weight = function(){
??return this.weight;
?};
?this.set_weight = function(weight){
??this.weight=weight;
?
?};

????? this.message = function(){
??????????? return "名稱為: " + this.get_name()+";\n"+"顏色為: "+this.get_color()+";\n"+"重量為: "+this.get_weight()+";\n"+"形狀為: "+this.get_shape()+";\n"
??????? };
}

?//javaScript中实现继承有多种方法,冒充对象,call(),apply()方法 以及通过原型链 prototype

子类 apple

有三种方法进行继承

function Apple(){
?//方法一??1 apply()方法
?//???? Fruit.apply(this,new Array());
//方法一? 2?apply()
????? Fruit.apply(this,arguments);???
//方法二 call() 方法
?//???? Fruit.call(this);???

//方法三 对象冒充

//? this.newApple= Fruit;

//? this.newApple();

//? delete this.newApple;
??? this.tree = '蘋果是長在蘋果樹上';
??? this.name1 = this.name;
??? this.detail = function(){
??????? return this.message()+this.tree;
??? };
??? //當我把detail當做一個屬性,把父类方法的返回值赋给detail是,結果是不合理的,
??? this.detail2 = this.message()+ this.tree;
??? this.get_detail2 = function(){
??????? return this.detail2+"\n";
??? };
}

赋值

var apple=new Apple();
apple.set_name('apple');
apple.set_weight(0.5);
apple.set_shape('圓形');
apple.set_color('red');

?

console.log("這是調用Fruit的message()方法 \n"+apple.message());
/*
結果為
這是調用Fruit的 message()方法
名稱為: apple;
顏色為: red;
重量為: 0.5;
形狀為: 圓形;
*/
console.log("這是調用apple的detail()方法 \n"+apple.detail());
/*
這是調用apple的 detail()方法
名稱為: apple;
顏色為: red;
重量為: 0.5;
形狀為: 圓形;
蘋果是長在蘋果樹上
*/

console.log("這是調用apple的detail1的屬性 \n"+apple.detail2);
/*這是調用apple的 detail1的屬性
*? 名稱為: fruit;
*顏色為: ;
*重量為: 0千克;
*形狀為: ;
*蘋果是長在蘋果樹上
*/
console.log("這是調用apple的get_detail1()的方法 \n"+apple.get_detail2());

?

思路方法是:

???? 个人觉得是实例化的时候detail2 属性是为空,所以当直接调用detail2 属性时,结果apply的各项属性也是为空.解决方法是通过子类新建一个方法对其detail2的值进行更新

this.detail2 = "";
this.get_detail2 = function(){
??????? this.detail2 = this.message()+ this.tree;
??????? return this.detail2;
??? };

?

//扩充 通过原型链prototype实现继承

function ClassA(){

??? ClassA.prototype.name = 'jack';??????????
}
ClassA.prototype.set_name = function(name){
??????? this.name = name;
};
ClassA.prototype.get_name = function(){
????????? return this.name;
};
function ClassB(){
????????? ClassB.prototype = new ClassA();
????????? console.log(ClassB.prototype.get_name());
}
ClassB();

?

?

?