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();
?
?
?