_new

说明

模拟实现new操作符

源码

用法

_new.test.ts
1
import { _new } from "../../utility/function/_new";
2
3
describe('_new', () => {
4
test('_new should return the instance of target constructor and received non parameter', () => {
5
function Person() { }
6
Person.prototype = {
7
constructor: Person,
8
say() {
9
return 'Person';
10
},
11
};
12
13
const received = [
14
Person,
15
];
16
const expected = [
17
{
18
constructor: Person,
19
say: 'Person',
20
},
21
];
22
23
for (const [i, v] of received.entries()) {
24
const result: any = _new(v);
25
26
expect(result.constructor).toBe(expected[i]['constructor']);
27
expect(result.say()).toBe(expected[i]['say']);
28
}
29
});
30
31
test('_new should return the instance of target constructor and received many of parameters', () => {
32
function Person(name: string, age: number) {
33
this.name = name;
34
this.age = age;
35
}
36
Person.prototype = {
37
constructor: Person,
38
say() {
39
return 'Person';
40
},
41
};
42
43
const received = [
44
Person,
45
];
46
const expected = [
47
{
48
name: 'ddzy',
49
age: 21,
50
constructor: Person,
51
say: 'Person',
52
},
53
];
54
55
for (const [i, v] of received.entries()) {
56
const result: any = _new(v, 'ddzy', 21);
57
58
expect(result.name).toBe(expected[i]['name']);
59
expect(result.age).toBe(expected[i]['age']);
60
expect(result.constructor).toBe(expected[i]['constructor']);
61
expect(result.say()).toBe(expected[i]['say']);
62
}
63
});
64
});
Copied!
最近更新 1yr ago
复制链接