我想要一个可以实例化的 javascript 函数,并捕获每个调用它的未定义方法(代理陷阱)。
到目前为止,我所拥有的是:
var MyProxyFunction = new Proxy(function () {
console.log(">>>>>>>>>>>>>>>>>>>> constructor");
}, {
get: function(target, prop) {
if (target[prop] === undefined) {
return function() {
console.log('an otherwise undefined function!!');
};
}
else {
return target[prop];
}
}
});
现在,如果我调用MyProxyFunction.foo()
,它会被调用(我会看到“构造函数”被触发,以及来自 get 函数的日志)。
但是我想做的是像这样实例化这个对象(并在构造函数中做一些初始化):
var myObj = new MyProxyFunction();
myObj.foo();
但是当我这样做时,我明白这foo()
不是一个功能。为什么?以及如何在实例化代理时使其工作?
该行为的解释是您的构造函数被代理,而不是它构造的对象。因此,当您编写new MyProxyFunction
代理构造函数时,会调用该构造函数,但该构造函数创建了一个与 无关的新对象Proxy
,而是与prototype
构造函数的属性有关。
有几种方法可以使它工作。
function MyProxyFunction() {
console.log(">>>>>>>>>>>>>>>>>>>> constructor");
};
MyProxyFunction.prototype = new Proxy(MyProxyFunction.prototype, {
get: function(target, prop) {
if (target[prop] === undefined) {
return function() {
console.log('an otherwise undefined function!!');
};
}
else {
return target[prop];
}
}
});
var myObj = new MyProxyFunction();
myObj.foo();
console.log('constructor:', myObj.constructor.name);
console.log('Is instance of MyProxyFunction?: ', myObj instanceof MyProxyFunction);
现在使用名称MyProxyFunction看起来有点奇怪,因为代理的不是函数(构造函数)本身。
如果你想要一个构造函数在你每次用它实例化一个对象时创建一个新的代理,那么不要new Proxy
直接赋值给MyProxyFunction
,而是让它成为一个简单的构造函数,返回一个new Proxy
.
然后您必须代理的对象是this
.
function MyProxyFunction() {
console.log(">>>>>>>>>>>>>>>>>>>> constructor");
return new Proxy(this, {
get: function(target, prop) {
if (target[prop] === undefined) {
return function() {
console.log('an otherwise undefined function!!');
};
}
else {
return target[prop];
}
}
});
}
var myObj = new MyProxyFunction();
myObj.foo();
console.log('constructor:', myObj.constructor.name);
console.log('Is instance of MyProxyFunction?: ', myObj instanceof MyProxyFunction);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句