Javascript继承与简洁的原型赋值语法(Javascript inheritance with

2019-10-19 01:08发布

我定义了使用这个(两个JavaScript类prototype )的方法:

function Parent () {
    this.a = 1;
}

Parent.prototype = {
    hello : function () {
        return "Hello I'm Parent!";
    },
    setA : function (a) {
        this.a = a;
    }
};

function Child () {
    this.b = 2;
}

Child.prototype = new Parent();
Child.prototype.constructor = Child;

Child.prototype = {
    hello : function () {
        return "Hello I'm Child!";
    },
    setB : function (b) {
        this.b = b;
    }
};

我使用这种技术,因为我认为标准语法它太冗长和稀疏:

Child.prototype.hello = function () {...};

Child.prototype.setB = function (b) {...};

这里的问题是,我重写 Child.prototype (继承自Parent )失去.setA()方法(但正确地覆盖 .hello()

合并的两个原型的解决方案? 怎么样?
这种方法可能会导致问题?

Answer 1:

被合并的两个原型的解决方案?

是。

怎么样?

只需编写运行在目标文字和每个属性合并到原型循环。

function inherit(Child, Parent, methods) {
    var p = Child.prototype = Object.create(Parent.prototype);
    p.constructor = Child;
    for (var m in methods)
        p[m] = methods[m];
    return p;
}
function Child () {
    Parent.call(this);
    this.b = 2;
}
inherit(Child, Parent, {
    hello : function () {
        return "Hello I'm Child!";
    },
    setB : function (b) {
        this.b = b;
    }
});


Answer 2:

这里有一个例子,我从职业的JavaScript设计模式复制

function extend (subClass, superClass) {
  var F = function () {};
  F.prototype = superClass.prototype;
  subClass.prototype = new F();
  subClass.prototype.constructor = subClass;

  subClass.superclass = superClass.prototype; 
  if (superClass.prototype.constructor === Object.prototype.constructor) {
    superClass.prototype.constructor = superClass;
  } // end if
} // end extend()

function Person (name) {
  this.name = name;
} // end Person()
Person.prototype.getName = function () {
  return this.name;
}; // end getName()

function Author (name, books) {
  Author.superclass.constructor.call(this, name); 
  this.books = books;
} // end Author()

extend(Author, Person);

Author.prototype.getBooks = function () {
  return this.books;
}; // end getBooks()
Author.prototype.getName = function () {
  var name = Author.superclass.getName.call(this);
  return name + " , author of " + this.getBooks();
}; // end getName()

var a = new Author("xxx", "xxx");
console.log(a.getName()); // xxx , author of xxx

笔者列出来实现继承三路:基于类,基于原型和增加基础。

你可以阅读代码,也许读的书..



文章来源: Javascript inheritance with concise prototype assignment syntax