On the trap of JavaScript prototype inheritance

Source: Internet
Author: User
Tags constructor inheritance

 javascript, as with other object-oriented languages, object types take the form of references. The variable holding the object is only an address, and the base type data is a value. When you store objects on a prototype, there may be traps

JavaScript defaults to prototype inheritance. Although there is no concept of Class (class), its functions (function) can act as constructors (constructor). Constructors combine this,new to build a Java-like class. As a result, JavaScript can simulate Class (class-based) inheritance by extending itself.   JavaScript is the same as other object-oriented languages, and object types take the form of references. The variable holding the object is only an address, and the base type data is a value. There may be traps when you store objects on a prototype.   See first example     code as follows: var create = function () {      function Fn () {}      Retu RN function (parent) {          Fn.prototype = parent          return new fn     } } ()     var parent = {      Name: ' Jack ',      Age: 30,      Ismarried:false}  var child = Create (parent)   Console.log (child)     Create worker The function implements a basic prototype inheritance, and every call to create copies a new object based on the parent object, and all attributes of the new object are derived from parent. Here the parent has three attributes, all basic data types: String, Number, Boolean.   then modify the child to see if it will affect parent     code as follows: Child.name = ' lily ' child.age = 20,  child.ismarried = True   Console.log (Child)   Console.log (parent)       ResultsThe following       that modifies the child does not affect parent.   Look at another example     code as follows: var create = function () {      function Fn () {}      RE Turn function (parent) {          Fn.prototype = parent          return n EW fn     } } ()     var parent = {      data: {        & nbsp Name: ' Jack ',          age:30,          Ismarried:false     },      Language: [' Java '] }  var child = Create (parent)     Child.data.name = ' Lily ' C Hild.data.age = 20  Child.data.isMarried = True Child.language.push (' JavaScript ')   Console.dir (child)   Console.dir (parent)   Note that the two attribute data,language of parent here are reference types, one is an object, the other is an array. The child still inherits from the parent, then modifies the child, and the results are as follows       can be seen, at this time the parent is also modified, and the child's name,age and so on. This is what you need to be aware of when using prototype inheritance.   The better way to use inheritance is to:   1, the data attribute adoptsClass inheritance (hanging on this) so that new can also pass the parameter configuration   2, the method adopts prototype inheritance, which can save memory, while the subclass overrides method does not affect the parent class   Below is a Write class tool function that satisfies the above 2 points     code as follows: /**   * @param {String} classname   * @param {string/function} supercls   * @param {functio n} factory   */function $class (name, superclass, factory) {      if (superclass = = ") Supercla SS = object      function clazz () {          if (typeof this.init = = ' function ') {              this.init.apply (this, arguments)          }&NBS P    }      var p = Clazz.prototype = new supercls      Clazz.prototype.constructor = clazz      Clazz.prototype.className = classname      var supr = supercls.prototype      Window[classname] = clazz      Factory.call (p, SUPR)  } The   object type is placed on the parent prototype, be careful when the subclass modifies it, and then Instances of all subclasses that inherit from the parent class will be modified. And this caused the BUG is not easy to find.   ES5 has added a new API to implement prototype inheritance: Object.create. You can use it instead of the implementation of the CREATE function above, as follows     code as follows: var parent = {      Name: ' Jack ',      age:30,& nbsp     Ismarried:false}  var child = object.create (parent)   Console.log (child)  
Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.