Skip to content

Commit

Permalink
fix(full): ensure prototype methods are copied;
Browse files Browse the repository at this point in the history
- Closes #24
  • Loading branch information
lukeed committed Sep 15, 2020
1 parent 81c1485 commit d8720a3
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/full.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export function klona(x) {
var i=0, k, list, tmp, str=Object.prototype.toString.call(x);

if (str === '[object Object]') {
tmp = typeof x.constructor === 'function' ? new x.constructor() : Object.create(null);
tmp = Object.create(x.__proto__ || null);
} else if (str === '[object Array]') {
tmp = Array(x.length);
} else if (str === '[object Set]') {
Expand Down Expand Up @@ -39,7 +39,7 @@ export function klona(x) {
}

if (tmp) {
for (list = Object.getOwnPropertySymbols(x); i < list.length; i++) {
for (list=Object.getOwnPropertySymbols(x); i < list.length; i++) {
set(tmp, list[i], Object.getOwnPropertyDescriptor(x, list[i]));
}

Expand Down
59 changes: 59 additions & 0 deletions test/suites/class.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,65 @@ export default function (klona) {
assert.equal(output.val, 42);
});

Classes('prototype methods :: manual', () => {
function Test() {}

Test.prototype = {
count: 0,
increment() {
this.count++;
}
};

const input = new Test();
const output = klona(input);

assert.equal(input.count, 0);
assert.equal(output.count, 0);

assert.equal(typeof input.increment, 'function');
assert.equal(typeof output.increment, 'function');

output.increment();
assert.equal(input.count, 0);
assert.equal(output.count, 1);

input.increment();
assert.equal(input.count, 1);
assert.equal(output.count, 1);
});

Classes('prototype methods :: class', () => {
class Test {
constructor() {
this.count = 0;
}
increment() {
this.count++
}
}

const input = new Test();
const output = klona(input);

assert.deepEqual(input, output);
assert.deepEqual(output.__proto__, Test.prototype);

assert.equal(input.count, 0);
assert.equal(output.count, 0);

assert.equal(typeof input.increment, 'function');
assert.equal(typeof output.increment, 'function');

output.increment();
assert.equal(input.count, 0);
assert.equal(output.count, 1);

input.increment();
assert.equal(input.count, 1);
assert.equal(output.count, 1);
});

Classes('constructor properties', () => {
function Test (num) {
this.value = num;
Expand Down

0 comments on commit d8720a3

Please sign in to comment.