有一道考复制的javascript题
迷茫
迷茫 2017-04-11 12:31:48
[JavaScript讨论组]

今天朋友面试时候碰到的一道面试题,原始代码里的内容是不能改的,最终目标是输出"我有3个APPLE"这句话
补充代码里的是我目前的答案,但是:

1.A.prototype.total=3这个写法有点搓,不知道怎么优化了

2.另外initialize这个方法应该如何调用呢?

下面上代码

    // 补充代码使得代码可以输出规定的内容
    // 原始代码 start
    var A = function() {
        this.name = 'apple';
    }
    A.prototype.getName = function() {
        return this.name;
    }
    // 原始代码 end
    //补充代码 start
    //浅复制对象,把参数内的方法名复制给A
    A.extend = function(source) {
      for(property in source){
        this.prototype[property]=source[property];
      }
      return this;
    }
    A.prototype.total=3;
    //补充代码 end

    //原始代码 start
    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.initialize());
    console.log(b.say()); //我有3个APPLE
    // 原始代码 end
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(4)
伊谢尔伦

简单写了写,可以参考一下:

A.extend = function(source) {

  this.initialize = this;//这句实在没想起有什么好方法,不修改超类

  var T = function(){};//下面两句主要使用原型式继承,避免直接new A()导致调用两次A中的代码
  T.prototype = this.prototype;

  var F = function(){
    this.initialize();
  };

  F.prototype = new T();
  F.prototype.superclass = this;
  F.prototype.getName = function(){//覆盖超类中的getName,返回大写的
    return this.name.toUpperCase();
  }
  for(var prop in source){
    F.prototype[prop] = source[prop];
  }

  return F;
}
PHP中文网

为了得到结果:

A.extend = function(source) {
  let ret  = function() {
    this.superclass = this
    this.superclass.initialize = A
    source.initialize.bind(this)()
  }
  ret.prototype = new A()
  for (let i in source) {
    if (i !== 'initialize') {
      ret.prototype[i]  = source[i]
    }
  }
  return ret
}
大家讲道理
A.extend = function(o) {
      function Cl(){
         this.initialize();
     }
     Cl.prototype = new A();
     Cl.constructor = A;
     for (var v in o){
Cl.prototype[v] = o[v];
     }
     Cl.prototype.superclass = this;
     this.initialize = function(){
         this.name = this.name.toUpperCase();
     };
      return Cl;
};
天蓬老师
var A = function() {
    this.name = 'apple';
}
A.prototype.getName = function() {
    return this.name;
}

function B(total){
    A.call(this);
    this.total=total;
}

B.prototype=(function(){
    var tempFun=function(){};
    tempFun.prototype=new A();
    return new tempFun();
}());

B.prototype.constructor=B;
B.prototype.say=function(){
    return '我有' + this.total + '个' + this.getName()
};

var instanceB=new B(3);
instanceB.say();
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号