Heim  >  Artikel  >  Web-Frontend  >  Beispiel für eine benutzerdefinierte gemischte JS-Mixin-Funktion

Beispiel für eine benutzerdefinierte gemischte JS-Mixin-Funktion

高洛峰
高洛峰Original
2016-12-05 10:11:481148Durchsuche

Das Beispiel in diesem Artikel beschreibt die benutzerdefinierte JS-Mixin-Funktion. Teilen Sie es als Referenz mit allen. Die Details lauten wie folgt:

<script type="text/javascript">
/* 增加函数 */
function augment(receivingClass, givingClass) {
 for(methodName in givingClass.prototype) {
  if(!receivingClass.prototype[methodName]) {
   receivingClass.prototype[methodName] = givingClass.prototype[methodName];
  }
 }
}
/* 改进的增加函数 */
function augment(receivingClass, givingClass) {
 if(arguments[2]) { // Only give certain methods.
  for(var i = 2, len = arguments.length; i < len; i++) {
   receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
  }
 }
 else { // Give all methods.
  for(methodName in givingClass.prototype) {
   if(!receivingClass.prototype[methodName]) {
    receivingClass.prototype[methodName] = givingClass.prototype[methodName];
   }
  }
 }
}
var Author = function Author(name, books) { // 构造函数
 this.name = name;
 this.books = books || &#39;default value&#39;;
};
Author.prototype = {
 getName: function() {
  return this.name;
 },
 getBooks: function() {
  return this.books;
 }
};
var Editor = function Editor() {
};
Editor.prototype = {
 hello: function() {
  return &#39;Hello,&#39;+this.name;
 }
};
augment(Author, Editor);
var author = new Author(&#39;Ross Harmes&#39;, [&#39;JavaScript Design Patterns&#39;]);
console.log(author.getName());
console.log(author.getBooks());
console.log(author.hello());
</script>

Nach dem Spleißvorgang hat der Autor die Hallo-Methode erhalten und das Attribut ist immer noch sein eigener Name.

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn