javascript - 今天面试碰到JS题,求解

查看:84
本文介绍了javascript - 今天面试碰到JS题,求解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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

解决方案

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

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

这篇关于javascript - 今天面试碰到JS题,求解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆