Home > Web Front-end > JS Tutorial > body text

JS custom mixed Mixin function example

高洛峰
Release: 2016-12-05 10:11:48
Original
1157 people have browsed it

The example in this article describes the JS custom mixin function. Share it with everyone for your reference, the details are as follows:

<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>
Copy after login

After the splicing process, the author has obtained the hello method, and the attribute is still his own name.

Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!