如何检测函数是用javascript调用的 [英] how to detect a function was called with javascript

查看:156
本文介绍了如何检测函数是用javascript调用的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个javascript函数。

I have a javascript function.

如何检查:


  • 如果调用了函数(在< head>< / head> 部分中有此函数),则不要调用函数

  • if function was called ( in <head></head> section have this function), then not to call the function

如果未调用函数(在< head>< / head> 部分中没有此函数),则调用功能

if function was not called ( in <head></head> section haven't this function), then call the function

require_once include_once PHP

推荐答案

两个选项:

静态变量以下是使用自调用函数在静态变量中创建静态变量(如C语言)的方法。

Static variables Here's how to create static (like in C) variables using self calling functions to store your static variables in a closure.

var myFun = (function() {
  var called = false;
  return function() {
    if (!called) {
      console.log("I've been called");
      called = true;
    }
  }
})()

空函数替换运行后将函数设置为空函数。

Empty Function replacement Set the function to an empty function after it runs.

function callonce() {
  console.log("I've been called");
  arguments.callee = function() {};
}

抽象的想法这是一个返回一个函数的函数只调用一次的函数,这样我们就不用担心将锅炉板代码添加到每个函数中。

Abstract the idea Here's a function that returns a function that only gets called once, this way we don't have to worry about adding boiler plate code to every function.

function makeSingleCallFun(fun) {
  var called = false;
  return function() {
    if (!called) {
       called = true;
       return fun.apply(this, arguments);
    }
  }
}

// Alternate implementation   
function makeSingleCallFun(fun) {
    return function() {
      return fun.apply(this, arguments);
      arguments.callee = function() {};
    }
}

var myFun = makeSingleCallFun(function() {
  console.log("I've been called");
});
myFun(); // logs I've been called
myFun(); // Does nothing

这篇关于如何检测函数是用javascript调用的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆