分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

js中自调用函数(一次性函数)

发布时间:2023-09-06 02:08责任编辑:顾先生关键词:js

1.函数的自调用---自调用函数

//函数的自调用//一次性函数(function (){console.log("一次性");})();(function(win){var num=20;win.num=num;})(window);//把局部变量给父类就可以了console.log(num);

2.通过自调用函数产生一个随机数对象,在自调用函数外面,调用该随机数对象方法产生随机数

//通过自调用函数产生一个随机对象(function(window){//产生一个随机function Random(){Random.prototype.getRandom=function(min,max){return Math.floor(Math.random()*(max-min)+min);};//把Random对象暴露给顶级对象window}window.Random=Random;})(window);var rm=new Random();console.log(rm.getRandom(0,5)); ?

3.案例一个随机小方块

<script> ?//产生随机数对象的 ?(function (window) { ???function Random() { ???} ???Random.prototype.getRandom=function (min,max) { ?????return Math.floor(Math.random()*(max-min)+min); ???}; ???//把局部对象暴露给window顶级对象,就成了全局的对象 ???window.Random=new Random(); ?})(window);//自调用构造函数的方式,分号一定要加上 ?//产生小方块对象 ?(function (window) { ???//console.log(Random.getRandom(0,5)); ???//选择器的方式来获取元素对象 ???var map=document.querySelector(".map"); ???//食物的构造函数 ???function Food(width,height,color) { ?????this.width=width||20;//默认的小方块的宽 ?????this.height=height||20;//默认的小方块的高 ?????//横坐标,纵坐标 ?????this.x=0;//横坐标随机产生的 ?????this.y=0;//纵坐标随机产生的 ?????this.color=color;//小方块的背景颜色 ?????this.element=document.createElement("div");//小方块的元素 ???} ???//初始化小方块的显示的效果及位置---显示地图上 ???Food.prototype.init=function (map) { ?????//设置小方块的样式 ?????var div=this.element; ?????div.style.position="absolute";//脱离文档流 ?????div.style.width=this.width+"px"; ?????div.style.height=this.height+"px"; ?????div.style.backgroundColor=this.color; ?????//把小方块加到map地图中 ?????map.appendChild(div); ?????this.render(map); ???}; ???//产生随机位置 ???Food.prototype.render=function (map) { ?????//随机产生横纵坐标 ?????var x=Random.getRandom(0,map.offsetWidth/this.width)*this.width; ?????var y=Random.getRandom(0,map.offsetHeight/this.height)*this.height; ?????this.x=x; ?????this.y=y; ?????var div=this.element; ?????div.style.left=this.x+"px"; ?????div.style.top=this.y+"px"; ???}; ???//实例化对象 ???var fd=new Food(20,20,"green"); ???fd.init(map); ???console.log(fd.x+"===="+fd.y); ?????})(window);</script>

  

js中自调用函数(一次性函数)

原文地址:https://www.cnblogs.com/liushisaonian/p/9425427.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved