new 和 class 重写
new
重写
Function.prototype.new = function () {
var fn = this
var obj = Object.create(fn.prototype)
var res = fn.apply(obj, arguments)
return res instanceof Object ? res : obj
}
function Person (name) {
this.name = name
}
Person.prototype.say = function () {
console.log('hello world')
}
var p = Person.new('zhangsan')
console.log(p)
p.say()
var p1 = new Person('zhangsan')
console.log(p1)
function Person1 (name) {
this.name = name
return {
age: 1
}
}
var p2 = Person1.new('zhangsan')
console.log(p2)
var p3 = new Person1('zhangsan')
console.log(p3)
class重写
function MyClass (name, age) {
"use strict"
var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : name
var age = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : age
if (typeof new.target === 'undefined') {
throw new Error('必须通过 new 执行')
}
this.name = name
this.age = age
}
var createClass = (function () {
function defineProperties(target, props) {
for(var i = 0; i < props.length; i++) {
var descriptor = props[i]
descriptor.enumerable = descriptor.enumerable || false
descriptor.configurable = descriptor.configurable || true
Object.defineProperty(target, descriptor.key, descriptor)
}
}
return function(constructor, protoProps, staticProps) {
if (protoProps) defineProperties(constructor.prototype, protoProps)
if (staticProps) defineProperties(constructor, staticProps)
}
})()
createClass(MyClass, [
{
key: "say",
value: function () {
console.log('hello world')
}
},
{
key: 'sayHi',
value: function () {
console.log('Hi')
}
}
], [
{
key: "test",
value: function () {
console.log('static')
}
}
])
var p = new MyClass('zhangsan', 18)
console.log(p)
for(var value in p) {
console.log(value)
}
MyClass('zhangsan', 18)