Last active
September 21, 2023 08:16
-
-
Save iwill/2303057 to your computer and use it in GitHub Desktop.
$class-2.0.0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* Javascript library - $class 2.0.0 | |
* https://gist.github.com/iwill/2303057 | |
*/ | |
export default function $class(source, SuperClass) { | |
// default values | |
SuperClass = SuperClass || Object; | |
source = source || {}; | |
// constructor & super constructor | |
source.constructor = source.hasOwnProperty("constructor") ? source.constructor : function() { | |
SuperClass.apply(this, arguments); | |
}; | |
// class & prototype | |
const Class = source.constructor; | |
Class.isPlainObject = true; | |
Class.prototype = new SuperClass(); | |
// override Class.prototype[each] by source[each] | |
for (let each in source) { | |
Class.prototype[each] = source[each]; // include `constructor` | |
} | |
return Class; | |
} | |
/** | |
* $class 1.0.0 | |
this.$class = function(src) { | |
src.constructor.prototype = src; | |
return src.constructor; | |
}; */ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
刚刚给
Class
增加了一个属性:Class.isPlainObject = true;
,用来说明它的实例是 plain object —— 所有的属性都可遍历、可修改。原本考虑用
Object.defineProperty(Class, "isPlainObject", { value: true });
避免isPlainObject
属性被修改,但是这好像偏离了本意,是的isPlainObject
本身也应该可遍历、可修改。做这个改动,主要源于最近用到的对
Object
的判断,判断的方法千奇百怪,逻辑其实有两种:Object
的直接实例,即所谓的 plain objectObject
子类的实例本来
Object
子类的实例也不该被区别对待的,可是有两种特殊情况:区分数组和对象,以及用遍历所有属性。前者还好,有Array.isArray()
可用,可是 ...期盼已久的 ES6 的
class
并不如想象中那样完美,虽然有了class
、extends
、constructor
、get
、set
、static
,也支持了私有属性,但是get
定义的属性不能遍历、不能序列化成JSON
,要用
Object.defineProperty(this, k, { value: v, enumerable: true })
或者
Object.defineProperties(this, { k: { value: v, enumerable: true } })
定义才行,不愧是 JavaScript 啊,一如既往的蛋疼。
所以,对
Object
的判断我偏向于 plain object 了。为了避免传统的function
+prototype
方式创建的 plain object 被误伤,我在$class
创建的Class
中添加了isPlainObject
属性,注意是Class
的属性,通过示例要这样访问object.constructor.isPlainObject
访问。参考: