我想寫一個類,處理未定義的屬性。我還想返回this
能夠鏈接方法來創建域特定語言 (DSL)。
我從構造函數返回一個代理,以處理未定義的屬性。現在在測試實例時,它確實發生了,這return this
並不能證明與實例相同。我擔心由此產生的錯誤,儘管我可以按預期鏈接方法。
這是一個顯示行為的摩卡 茶測試。替換o.that().should.not.equal(o);
上o.that().should.equal(o);
一條指令中的with以查看它是如何失敗的。
require('chai').should();
describe('chai testing classes using Proxy', () => {
it('asserts object identity, if an instance method returns this', () => {
const o = new class NormalClass{ }
o.that = function() { return this; }
o.that().should.equal(o);
});
it('observes the same behaviour for constructors returning a dummy Proxy', () => {
const o = new class ProxyClass{
constructor() { return new Proxy(this, {}); }
}
o.that = function() { return this; }
o.that().should.equal(o);
});
it('requires deep.equal on the other hand, if the Proxy handles get', () => {
const o = new class ProxyClassPlusGet{
constructor() {
return new Proxy(this, {
get: function(target, prop) { return target[prop]; },
});
}
}
o.that = function() { return this; }
o.that().should.deep.equal(o);
o.that().should.not.equal(o);
});
});
您的實現在o.that() === o
產量範圍內有效true
。
但它不適用於 getter,這會干擾 chai 的should
. 你可以用
const o = new Proxy({
get self() { return this; },
that() { return this; },
}, {
get(target, prop) { return target[prop]; },
});
console.log(o.self === o);
console.log(o.that() === o);
這是為什麼?因為你的get
陷阱被打破了,忽略了屬性訪問的接收者。這將舉行代理o
,但是當你這樣做return target[prop]
,然後target
將接收器。您可以使用Reflect.get
以下方法修復它:
const o = new Proxy({
get self() { return this; },
that() { return this; },
}, {
get(target, prop, receiver) {
return Reflect.get(target, prop, receiver);
// ^^^^^^^^
},
});
console.log(o.self === o);
console.log(o.that() === o);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句