Skip to content

Instantly share code, notes, and snippets.

@lin
Created May 30, 2019 04:21
Show Gist options
  • Save lin/ef51dff8ff4c691aed4df27646d57bf2 to your computer and use it in GitHub Desktop.
Save lin/ef51dff8ff4c691aed4df27646d57bf2 to your computer and use it in GitHub Desktop.
var Mixin = {}
Mixin.mix_into_prototype = function() {
for (var i = 0; i < arguments.length; i++) {
let current_object = arguments[i]
for (let key in current_object) {
this[key] = current_object[key]
}
}
return this;
}
// by using mixin as the __proto__ at the first time
// by using the caller as the __proto__ in the future
Mixin.create_prototype = function () {
let is_create_with_no_object = (arguments.length == 0)
if (is_create_with_no_object) {
return Object.create(this) // return an instance of mixin
} else {
let an_empty_object_inherit_caller = Object.create(this)
let other_objects_to_mixin = arguments
return this.mix_into_prototype.apply(an_empty_object_inherit_caller, other_objects_to_mixin)
}
}
// by using the caller as the __proto__ in the future
Mixin.generate_constructor = function () {
let an_empty_object_inherit_caller = Object.create(this)
let other_objects_to_mixin = arguments
let mixined_Mixin_instance = Mixin.mix_into_prototype.apply(an_empty_object_inherit_caller, other_objects_to_mixin)
let Klass = mixined_Mixin_instance.constructor
Klass.prototype = mixined_Mixin_instance;
return Klass;
}
let a = {
constructor: function Set_constructor (name, age) {
this.name = name;
this.age = age;
},
toString: function albert(){return 'albert'},
proto_name: 'albert',
proto_age: 12
}
let b = {
salary: 12,
dept: 'hr'
}
let d = {
aaa: 12,
debbbpt: 'hr'
}
let cls = Mixin.generate_constructor(a, b);
// function cls (name, age){// a.constructor
// this.name = 'name';
// this.age = age;
// }
// cls.prototype = {
// constructor: cls
// __proto__: caller of generate_constructor
// ...a
// ...b
// }
// // an_empty_object_inherit_caller
// // then mixin a and b
let c = new cls('c', 11);
// {
// name: 'al',
// age: 12,
// __proto__: cls.prototype // c.__proto__.__proto__ = Mixin
// }
let e = c.create_prototype(d)
// {
// constructor: c.constructor
// __proto__: c
// ..d
// }
let f = e.generate_constructor()
// function f (name, age){ // a.constructor
// this.name = 'name';
// this.age = age;
// }
// f.prototype = {
// constructor: f
// __proto__: e
// ..d
// }
// // an_empty_object_inherit_caller
// // then mixin a and b
let g = new f('g', 11111) // g.__proto__ = f.prototype
console.log(g.__proto__.__proto__.__proto__.__proto__)
exports.Mixin = Mixin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment