仅供参考,我正在尝试遵循Abstract Encoding规范。本质上,我想创建一个“函数变量” let foo = codec.encode
,其中encode()
调用codec
中的另一个函数,并且我可以访问foo.bytes
。看来我可以访问bytes
的值,但不能访问内部函数this.encodingLength()
,或创建绑定函数变量,并且发生完全相反的情况。仅当我将函数encode()
分配给变量时,才会发生此问题。我在某处读到bind()
创建了一个包装函数(将无法访问bytes
,并且如果对象函数没有正确的上下文,则对象函数将无法访问其他对象函数。有可能同时拥有两个世界?
示例代码:
const codec = {
encode: function encode () {
encode.bytes = 2
this.encodingLength()
},
encodingLength: function encodingLength () { }
}
let foo = codec.encode
let bar = codec.encode.bind(codec)
> foo()
TypeError: this.encodingLength is not a function
at encode (repl:4:6)
> foo.bytes
2
> bar()
undefined
> bar.bytes
undefined
也使用this.encode.bytes
似乎没什么作用
const codec = {
encode () {
this.encode.bytes = 2
this.encodingLength()
},
encodingLength () { }
}
答案 0 :(得分:1)
这对您有用吗?
// define encodingLength function here
function encodingLength(object) {
// determine encoding length of obj here
return 5; // dummy value
}
const codec = {
encode: function encode(object, buffer, offset) {
// encode object here
// capture `encodingLength` in a closure
encode.bytes = encodingLength(object); // dummy value
return []; // dummy empty "buffer"
},
decode: function decode(buffer, start, end) {
// decode buffer here
decode.bytes = 12; // another dummy value
return {}; // dummy "decoded" object
},
encodingLength: encodingLength
};
let foo = codec.encode;
foo();
console.log(foo.bytes); // 5, as expected
console.log(codec.encode.bytes); // 5, as expected
let bar = codec.decode;
bar();
console.log(bar.bytes); // 12, as expected
console.log(codec.decode.bytes); // 12, as expected
答案 1 :(得分:0)
请保持简单,不要使用this
:
const codec = {
encode() {
codec.encode.bytes = 2;
codec.encodingLength();
// ^^^^^
},
encodingLength() {},
};
答案 2 :(得分:0)
您可以执行以下操作:
const Codec = (function() {
let bytes = 2;
return {
encode,
encodingLength
};
function encode() {
bytes++;
encodingLength();
}
function encodingLength() {
console.log(`bytes: ${bytes}`);
}
});
const foo = new Codec();
foo.encode(); // output: bytes: 3
const bar = new Codec();
bar.encode(); // output: bytes: 3