Javascript Internal principles [javascript aggregation]

Source: Internet
Author: User

Javascript can not only implement inheritance, but sometimes we only need some attributes or methods in the class, so we can consider aggregation to implement

For example, here is just a train of thought. The example is not very detailed. for a deeper understanding of aggregation, you can refer to Baidu or discuss it together in the comments.

Object implementation method:

/*** Metadata classes ** sometimes do not require strict inheritance. What we really need is some functions in a class */(function () {// The var JSON = {toJSONString: function () {var output = []; for (key in this) {output. push (key + "-->" + this [key]);} return output;}/*** aggregate function */function mixin (receivingClass, givingClass) {for (methodName in givingClass) {if (! ReceivingClass [methodName]) {receivingClass [methodName] = givingClass [methodName] ;}} var o ={ name: "jim", age: 16}; mixin (o, JSON); document. write (o. toJSONString (). join (","));

Class implementation
JSON. prototype = {// If prototypetoJSONString: function () {var outPut = []; for (key in this) {outPut. push (key + "-->" + this [key])} return outPut ;}// create the aggregate function mixin (receivingClass, givingClass) {for (methodName in givingClass. prototype) {// if this function does not exist in this class, I will aggregate it. Otherwise, skip if (! ReceivingClass. prototype [methodName]) {receivingClass. prototype [methodName] = givingClass. prototype [methodName] }}// var o = {name: "a", age: 27} var o = function () {this. name = "a"; this. age = 17} mixin (o, JSON); var a = new o (); document. write (. toJSONString (). join (","))

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.