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 believe that in some cases, the prototype pattern can provide certain conveniences, but in complex applications, prototype-based object-oriented systems are unsatisfactory in terms of abstraction and inheritance. 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.
Prototype-based object-oriented language
The prototype pattern, like the class pattern, is a programming generic, that is, a programming methodology. In addition, functional programming, which 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);
The purpose of the prototype pattern is not to obtain an exact object, but to provide a convenient way to create objects (from "JavaScript Design Patterns and Development Practices"). However, due to language design issues, JavaScript's prototype has many contradictions. 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)
Actually, 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}
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 you use the new operator on a function, the value of the function's prototype property 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; }
As can be seen from the above, although using the new operator to call a function looks like using template instantiation to create an object, the essence is to clone a new object using a prototype object.
Because the newly cloned object can access all methods and properties of the prototype object, coupled with the characteristics of the new operator, this becomes the cornerstone of using prototypes to simulate class languages.
Use prototypes to simulate class languages
Abstract
Use the prototype pattern to simulate classes, first 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 have the concept of a constructor), and places methods 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); };
Inherit
Inheritance is one of the most talked about concepts in OO languages. Many OO languages support two types of inheritance: interface inheritance and implementation inheritance. Interface inheritance inherits method signatures, while implementation inheritance inherits the actual methods. However, interface inheritance cannot be implemented in ECMAScript. It only supports implementation inheritance, and its implementation inheritance mainly relies on the prototype chain. (From "JavaScript Advanced Programming" Section 6.3 - Inheritance) In the third year of high school, the author explored various simulations of inheritance, such as: combined inheritance, prototype inheritance, parasitic inheritance, parasitic combination inheritance, and finally parasitic combinations became all simulation classes The basis of inheritance.
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); }
高三中只给出了单继承的解决方案,关于多继承的模拟我们还得自己想办法。由于多继承有其本身的困难:面向对象语言如果支持了多继承的话,都会遇到著名的菱形问题(Diamond Problem)。假设存在一个如左图所示的继承关系,O中有一个方法foo,被A类和B类覆写,但是没有被C类覆写。那么C在调用foo方法的时候,究竟是调用A中的foo,还是调用B中的foo?
所以大多数语言并不支持多继承,如Java支持单继承+接口的形式。JavaScript并不支持接口,要在一个不支持接口的语言上去模拟接口怎么办?答案是著名的鸭式辨型。放到实际代码中就是混入(mixin)。原理很简单:
function mixin(t, s) { for (var p in s) { t[p] = s[p]; } }
值得一提的是dojo利用MRO(方法解析顺序(Method Resolution Order),即查找被调用的方法所在类时的搜索顺序)方式解决了多继承的问题。
到此,我们已经清楚了模拟类语言的基本原理。作为一个爱折腾的程序员,我希望拥有自己的方式来简化类的创建:
最终,在借鉴各位大牛的知识总结,我编写了自己的类创建工具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);
类创建方式如下:
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('lzz'); console.log(p.Name);//lzzAttribute console.log(Person);
继承:
var Employee = Person.derive({//子类有父类派生 constructor: function(name, age) { this.setInfo(name, age); }, statics: { declaredClass: "Employee" }, setInfo: function(name, age) { this._super('setInfo', name);//调用父类同名方法 this.age = age; } }); var e = new Employee('lll', 25); console.log(e.Name);//lllAttribute console.log(Employee);
以上就是本文的全部内容,希望对大家的学习有所帮助。