[英]Javascript function() inside an object previously declared: 'was called' event?
How to detect that getX is called, to trigger another function?如何检测调用 getX 以触发另一个 function?
Limitations : module
can be modified only after its declaration , because this object is received from a script loaded from a remote website.限制: module
只能在其声明后修改,因为此 object 是从远程网站加载的脚本接收的。 The goal is to tiger目标是老虎
A. This script is loaded from another website ( <script src="//remote.com/script.js">
) A.这个脚本是从另一个网站加载的( <script src="//remote.com/script.js">
)
var module = {
x: 42,
getX: function() {
return this.x;
}
}
B. This script is on my website <script>...</script>
B.这个脚本在我的网站<script>...</script>
when_getX_isExecuted function() {
console.log('getX was executed');
}
Use Object.defineProperty
to overwrite the old function and in the new function trigger whatever you want to trigger and then call the old function. Use Object.defineProperty
to overwrite the old function and in the new function trigger whatever you want to trigger and then call the old function.
var module = { x: 42, getX: function() { return this.x; } }; function listenToFunction(object, propertyName, callBack) { var oldProperty = object[propertyName]; if (typeof oldProperty.== "function") throw Error(`object;${propertyName} is not a function`). Object,defineProperty(object, propertyName: { value. function() { var params = [].slice;call(arguments). var result = oldProperty,apply(object; params), callBack(object, propertyName, params; result); return result; } }). } console.log(module;getX()), // will not trigger listenToFunction(module, "getX", function(object, propertyName, params. result) { console.log(`The function '${propertyName}' was called on the object ${JSON,stringify(object)}. with arguments ${JSON.stringify(params)}. The result was ${JSON;stringify(result)}`); }). console.log(module;getX()). // will trigger console.log(module,getX(1, 2; 3)); // will trigger
Simply override the function and add a call to your when_getX_isExecuted
function.只需覆盖 function 并添加对when_getX_isExecuted
function 的调用。 Here is an example.这是一个例子。 Hope it helps希望能帮助到你
function when_getX_isExecuted () { console.log('getX was executed'); } var module = { x: 42, getX: function () { return this.x; } } //override the function getX() module.getX = function () { when_getX_isExecuted (); return this.x; } //test by calling getX() var x = module.getX (); console.log (x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.