JavaScript 封装函数 ?

var d = new Date();
var txt = document.getElementById('textfield');

function settime(){
s = new Date();
txt.value = Math.ceil((s-d)/1000);
s = null;
anyt = setTimeout("settime()",1000);
}
我不想Javascript里出现全局变量,如何把上面的语句封装到一个函数中,以致能让我在window.load事件中调用他。

青春有我
浏览 578回答 3
3回答

临摹微笑

  函数封装是一种函数的功能,它把一个程序员写的一个或者多个功能通过函数、类的方式封装起来,对外只提供一个简单的函数接口。当程序员在写程序的过程中需要执行同样的操作时,程序员(调用者)不需要写同样的函数来调用,直接可以从函数库里面调用。程序员也可以从网络上下载的功能函数,然后封装到编译器的库函数中,当需要执行这一功能的函数时,直接调用即可。而程序员不必知道函数内部如何实现的,只需要知道这个函数或者类提供什么功能。  C语言函数封装举例:  func1(.....)  {  .....  .....  }  func2(......)  {  .....  .....  }  func3(.....)  {  func1(....)  {  func2(...)  {  }  }  能将func1和func2封装成一个DLL,能够直接让func3调用:  写一个DLL即可,把fun1和fun2写进去,举个例子:在DLL中写入://MyDll.h extern "C" _declspec(dllexport) int Max(int a, int b); //MyDll.cpp#include "windows.h"#include "MyDll.h"int Max(int a, int b) { if(a>=b)return a; else return b; } 在console应用程序中写入:#include "stdio.h" #include "stdlib.h" extern "C" _declspec(dllexport) int Max(int a, int b); #pragma comment(lib,"MyDll.lib") int main() { int a; a = Max(10, 5); printf("%d \n", a); return 0; } 

Helenr

function settime(){if(!window.myDate)window.myDate = new Date();if(!window.myField)window.myField = document.getElementById('textfield');var s = new Date();window.myField.value = Math.ceil((s-window.myDate)/1000);s = null;anyt = setTimeout("settime()",1000);}或者var myDate,myField;function settime(){if(!myDate)myDate = new Date();if(!myField)myField = document.getElementById('textfield');var s = new Date();myField.value = Math.ceil((s-myDate)/1000);s = null;anyt = setTimeout("settime()",1000);}

拉风的咖菲猫

无全局变量.var test=function(){var i=0;function cont(){document.getElementById('textfield').value=i;i++}function timer(){setInterval(cont,1000);}return{timer:timer}}()window.onload=test.timer;
打开App,查看更多内容
随时随地看视频慕课网APP