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

Detailed explanation of JS object-oriented programming

高洛峰
Release: 2017-03-12 14:16:29
Original
995 people have browsed it

This article mainly introduces JS object-oriented programming in detail to help you learn JS object-oriented in more detail. Interested friends can refer to it

Preface
When discussing object-oriented in the big world of JavaScript, two points must be mentioned: 1. JavaScript is an object-oriented language based on prototypes 2. The object-oriented approach of simulating class languages. As for why it is necessary to simulate the object-oriented nature of class languages, I personally think: In some cases, Prototype pattern can provide certain conveniences, but in complex applications, prototype-based object-oriented systems have problems with abstraction and The inheritance aspect is unsatisfactory. Since JavaScript is the only scripting language supported by major browsers, experts from all walks of life have to use various methods to improve the convenience of the language. The result of optimization is that the code they write becomes more and more like object-oriented in class languages. method, thereby also concealing the essence of the JavaScript prototype system.  

Object-oriented language based on prototype
The prototype pattern, like the class pattern, is a programming generic, that is, a programming methodology. In addition, the function programming that has become popular recently is also a kind of programming generics. When Brendan Eich, the father of JavaScript, designed JavaScript, he did not intend to add the concept of classes to it from the beginning. Instead, he drew on two other prototype-based languages: Self and Smalltalk.

Since they are both object-oriented languages, they must have methods to create objects. In a class language, objects are created based on templates. First, a class is defined as an abstraction of the real world, and then the object is instantiated by the class. In a prototype language, an object is created by cloning another object. The cloned parent Called a prototype object.

The key to cloning is whether the language itself provides us with a native cloning method. In ECMAScript5, Object.create can be used to clone objects.


var person = {
  name: "tree",
  age: 25,
  say: function(){
    console.log("I'm tree.")
  }
};

var cloneTree = Object.create(person);
console.log(cloneTree);
Copy after login

The purpose of the prototype pattern is not to get an exact object, but to provide a convenient way to create objects (from "JavaScript Design Pattern and Development Practice”). However, due to language design issues, there are many contradictions in JavaScript's prototype. Some of its complex syntax looks like those of class-based languages. These grammatical problems cover up its prototype mechanism (from "The Essence of JavaScript Language"). Such as:


function Person(name, age){
  this.name = name;
  this.age = age;      
}

var p = new Person('tree', 25)
Copy after login

In fact, when a function object is created, the function object generated by the Function constructor will run some code similar to this:


this.prototype = {constructor: this}
Copy after login

The new function object is assigned a prototype attribute, whose value is an object containing the constructor attribute and the attribute value is the new function. When using the newoperator on a function, the value of the function's prototype attribute is used as the prototype object to clone a new object. If the new operator is a method, its execution process is as follows:


Function.prorotype.new = function() {
  //以prototype属性值作为原型对象来克隆出一个新对象
  var that = Object.create(this.prorotype);
  
  //改变函数中this关键指向这个新克隆的对象
  var other = this.apply(that, arguments);
  
  //如果返回值不是一个对象,则返回这个新克隆对象
  return (other && typeof other === 'object') ? other : that;
}
Copy after login

As can be seen from the above, although calling a function using the new operator looks like Use template instantiation to create objects, but the essence is to clone new objects from prototype objects.

Since the newly cloned object can access all methods and properties of the prototype object, coupled with the characteristics of the new operator, this has become the cornerstone of using prototypes to simulate class languages.

Use prototypes to simulate class languages
Abstract

Use the prototype pattern to simulate classes, first of all, in an abstract way. According to the characteristics of the JavaScript language, usually a class (actually a pseudo-class) usually places fields in the constructor (actually a function called by the new operator, JavaScript itself does not There is no concept of constructor), and the method is placed in the prototype attribute of the function.


function Person(name, age) {
  this.name = name;
  this.age = age;
};

Person.prototype.say = function(){
  console.log("Hello, I'm " + this.name);
};
Copy after login

Inheritance

  继承是OO语言中的一个最为人津津乐道的概念。许多OO语言都支持两种继承方式:接口继承和实现继承。接口继承之继承方法签名,而实现继承则继承实际的方法。但是ECMAScript中无法实现接口继承,只支持实现继承,而且其实现继承主要是依靠原型链来实现的。(出自《JavaScript高级程序设计》 6.3节——继承)在高三中作者探索了各种关于继承的模拟,如:组合继承、原型继承、寄生继承、寄生组合继承,最终寄生组合式成为所有模拟类式继承的基础。


function Person(name, age) {
  this.name = name;
  this.age = age;
};

Person.prototype.say = function(){
  console.log("Hello, I'm " + this.name);
};

function Employee(name, age, major) {
  Person.apply(this, arguments);
  this.major = major;
};

Employee.prototype = Object.create(Person.prototype);
Employee.prorotype.constructor = Employee;

Employee.prorotype.sayMajor = function(){
  console.log(this.major);
}
Copy after login

  高三中只给出了单继承的解决方案,关于多继承的模拟我们还得自己想办法。由于多继承有其本身的困难:面向对象语言如果支持了多继承的话,都会遇到著名的菱形问题(Diamond Problem)。假设存在一个如左图所示的继承关系,O中有一个方法foo,被A类和B类覆写,但是没有被C类覆写。那么C在调用foo方法的时候,究竟是调用A中的foo,还是调用B中的foo?

Detailed explanation of JS object-oriented programming

  所以大多数语言并不支持多继承,如Java支持单继承+接口的形式。JavaScript并不支持接口,要在一个不支持接口的语言上去模拟接口怎么办?答案是著名的鸭式辨型。放到实际代码中就是混入(mixin)。原理很简单:


 function mixin(t, s) {
    for (var p in s) {
      t[p] = s[p];
    }
  }
Copy after login

  值得一提的是dojo利用MRO(方法解析顺序(Method Resolution Order),即查找被调用的方法所在类时的搜索顺序)方式解决了多继承的问题。  

  到此,我们已经清楚了模拟类语言的基本原理。作为一个爱折腾的程序员,我希望拥有自己的方式来简化类的创建:

  • 提供一种便利的方式去创建类,而不暴露函数的prototype属性

  • 在子类中覆盖父类方法时,能够像Java一样提供super函数,来直接访问父类同名方法

  • 以更方便的方式添加静态变量和方法而不去关心prototype

  • C#那样支持Attribute   

最终,在借鉴各位大牛的知识总结,我编写了自己的类创建工具O.js:


(function(global) {
  var define = global.define;
  if (define && define.amd) {
    define([], function(){
      return O;
    });
  } else {
    global.O = O;
  }

  function O(){};

  O.derive = function(sub) {
    debugger;
    var parent = this;
    sub = sub ? sub : {};

    var o = create(parent);
    var ctor = sub.constructor || function(){};//如何调用父类的构造函数?
    var statics = sub.statics || {};
    var ms = sub.mixins || [];
    var attrs = sub.attributes || {};

    delete sub.constructor;
    delete sub.mixins;
    delete sub.statics;
    delete sub.attributes;

    //处理继承关系
    ctor.prototype = o;
    ctor.prototype.constructor = ctor;
    ctor.superClass = parent;
    //利用DefineProperties方法处理Attributes
    //for (var p in attrs) {
      Object.defineProperties(ctor.prototype, attrs);
    //}
    //静态属性
    mixin(ctor, statics);
    //混入其他属性和方法,注意这里的属性是所有实例对象都能够访问并且修改的
    mixin(ctor.prototype, sub);
    //以mixin的方式模拟多继承
    for (var i = 0, len = ms.length; i < len; i++) {
      mixin(ctor.prototype, ms[i] || {});
    }

    ctor.derive = parent.derive;
    //_super函数
    ctor.prototype._super = function(f) {
      debugger;
      return parent.prototype[f].apply(this, Array.prototype.slice.call(arguments, 1));
    }

    return ctor;
  }

  function create(clazz) {
    var F = function(){};
    F.prototype = clazz.prototype;
    //F.prototype.constructor = F; //不需要
    return new F();
  };

  function mixin(t, s) {
    for (var p in s) {
      t[p] = s[p];
    }
  }
})(window);
Copy after login

类创建方式如下:


var Person = O.derive({
  constructor: function(name) {//构造函数
    this.setInfo(name);
  },
  statics: {//静态变量
    declaredClass: "Person"
  },
  attributes: {//模拟C#中的属性
    Name: {
      set: function(n) {
        this.name = n;
        console.log(this.name);
      },
      get: function() {
        return this.name + "Attribute";
      }
    }
  },
  share: "asdsaf",//变量位于原型对象上,对所有对象共享
  setInfo: function(name) {//方法
    this.name = name;
  }
});
var p = new Person(&#39;lzz&#39;);
console.log(p.Name);//lzzAttribute
console.log(Person);
Copy after login

继承:


var Employee = Person.derive({//子类有父类派生
  constructor: function(name, age) {
    this.setInfo(name, age);
  },
  statics: {
    declaredClass: "Employee"
  },
  setInfo: function(name, age) {
    this._super(&#39;setInfo&#39;, name);//调用父类同名方法
    this.age = age;
  }
});

var e = new Employee(&#39;lll&#39;, 25);
console.log(e.Name);//lllAttribute
console.log(Employee);
Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助。

The above is the detailed content of Detailed explanation of JS object-oriented programming. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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!