javascript - 今天面试碰到JS题,求解
大家讲道理
大家讲道理 2017-04-11 12:00:50
0
2
188

以下是题目,需要补充代码。自认不才,特来求助各位大神,望指点迷津.
题目是让补全 A 的代码,让这个代码可以跑起来,输出对应的结果

var A = function () {
    this.name = 'apple';
}
A.prototype.getName = function () {
    return this.name;
}

//补充代码

var B = A.extend({
    initialize: function () {
        this.superclass.initialize.call(this);
        this.total = 3;
    },
    say: function () {
        return '我有' + this.total + '个' + this.getName()
    }
});
    var b = new B();
    console.log(b.say());//我有3个apple;
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回覆(2)
巴扎黑

写了一个方法,写得不好的地方还请大佬们指教:

var A = function() {
    this.name = 'apple';
}

A.prototype.getName = function() {
    return this.name;
}

A.extend = function(obj) {

    A.prototype.initialize = function() {}

    var f = function() {
        this.superclass = new A();
        this.initialize();
    }
    
    f.prototype = Object.assign(new A(), obj);

    return f;
}

var B = A.extend({
    initialize: function() {
        this.superclass.initialize.call(this);
        this.total = 3;
    },
    say: function() {
        return '我有' + this.total + '个' + this.getName();
    }
});

var b = new B();
console.log(b.say());
阿神

你的问题是什么?是问extend 这个函数的实现吗?
好像没写原生代码,都用es6 对象继承了。。
补充一下

var A = function () {
    this.name = 'apple';
}
A.prototype.getName = function () {
    return this.name;
}
//补充代码

A.prototype.initialize = function(){
    this.total = 0 ;
}

A.extend  = function(protos){
    var a = new A(); 
    var b =  function(){
            this.superclass = a
            this.initialize();            
    }

    b.prototype = new A();
    
    if(!!protos){
        for(var p in protos){
            if(protos.hasOwnProperty(p)){
                b.prototype[p]= protos[p];
            }
        }
    }    
    return b;
}


var B = A.extend({
    initialize: function () {        
        this.superclass.initialize.call(this);
        this.total = 3;
    },
    say: function () {
        return '我有' + this.total + '个' + this.getName()
    }
});
var b = new B();
console.log(b.say());//我有3个apple;
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!