首页 新闻 会员 周边

JavaScript代码的小小疑问(58)——关于继承

0
[已解决问题] 解决于 2015-10-24 19:30
/***************************
*
*Js中父子“类”,子继承父,有些资料上说
*要实现继承,走三步:1. 在子类Sub中添
*加Super.call(this,arg); 2. 父的原型赋给
*子; 3. 父的构造函数赋给子; 这样就完成
*继承。这样子就可以用父的所有定义。
*
***************************/

function Super(){
    this.x = 0;
    this.y = 0;
    this.method = function(){
    //TO DO
  }
};


function Sub(){
    Super.call(this);  //1
};

Sub.prototype = Object.create(Super.prototype);    //2
Sub.prototype.constructor =Sub;    /*3  这一步不理解?为何不是 Sub.prototype.constructor =Super.prototype.constructor; ? */
Coca-code的主页 Coca-code | 初学一级 | 园豆:10
提问于:2015-10-24 16:37
< >
分享
最佳答案
0

http://www.cnblogs.com/humin/p/4556820.html

奖励园豆:5
幻天芒 | 高人七级 |园豆:37175 | 2015-10-24 16:49

你好,帮我看看这段代码要做怎么样的修改,才能console features为[‘eat’],现在为空。

function Animal(name) {
    // 属性
    this.name = name || 'Animal';
    // 实例方法
    this.sleep = function() {
        console.log(this.name + '正在睡觉!');
    }
    //实例引用属性
    this.features = [];
}

function Cat(name){
    Animal.call(this);
    this.name = name || "Bruce.Yin";
};

(function(){
    function Super(){};
    Super.prototype = Animal.prototype;
    Cat.prototype = new Super();
})();

var aHua = new Cat();
var aHei = new Cat();
aHua.features.push('eat');
console.log(aHua.sleep());  //Bruce.Yin正在睡觉!
console.log(aHei.features);  //[]

 

Coca-code | 园豆:10 (初学一级) | 2015-10-24 20:19

@Coca-code: 

function Animal(name) {
    // 属性
    this.name = name || 'Animal';
    // 实例方法
    this.sleep = function() {
        console.log(this.name + '正在睡觉!');
    }
    //实例引用属性
    //this.features = [];
}

function Cat(name){
    Animal.call(this);
    this.name = name || "Bruce.Yin";
};

(function(){
    function Super(){};
    Super.prototype = Animal.prototype;
    Cat.prototype = new Super();
    Cat.prototype.features = [];
})();

var aHua = new Cat();
var aHei = new Cat();
aHua.features.push('eat');
console.log(aHua.sleep());  //Bruce.Yin正在睡觉!
console.log(aHei.features);  //[]
幻天芒 | 园豆:37175 (高人七级) | 2015-10-25 13:32

@幻天芒: 解决了。

//实例引用属性

//this.features = [];

这行代码最好不注释掉,实现上面问题...

比如再有个Bird();子类实例,又要写一遍Bird.prototype.features = [];

...

Coca-code | 园豆:10 (初学一级) | 2015-10-25 13:49

@Coca-code: 要共享的话,就是构建原型属性。

幻天芒 | 园豆:37175 (高人七级) | 2015-10-26 13:57

@幻天芒: http://q.cnblogs.com/q/76990/

这个换行怎么写?

Coca-code | 园豆:10 (初学一级) | 2015-10-31 11:48
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册