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

以下是题目,需要补充代码。自认不才,特来求助各位大神,望指点迷津.
题目是让补全 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;
大家讲道理
大家讲道理

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

répondre à tous(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;
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!