开发者社区 问答 正文

实现一个继承

实现一个继承

展开
收起
kun坤 2019-11-28 14:06:50 267 分享 版权
1 条回答
写回答
取消 提交回答
  • function Parent(name) {
      this.name = name;
    }
    
    Parent.prototype.sayName = function() {
      console.log("parent name:", this.name);
    };
    
    function Child(name, parentName) {
      Parent.call(this, parentName);
      this.name = name;
    }
    
    function create(proto) {
      function F() {}
      F.prototype = proto;
      return new F();
    }
    Child.prototype = create(Parent.prototype);
    Child.prototype.sayName = function() {
      console.log("child name:", this.name);
    };
    
    Child.prototype.constructor = Child;
    var parent = new Parent("汪某");
    parent.sayName(); // parent name: 汪某
    var child = new Child("son", "汪某");
    
    
    2019-11-28 14:06:58
    赞同 展开评论
问答地址: