1、JS对象(方法、属性)
定义对象、方法、属性
<script>
// 创建对象1
var obj1 = new Object();
obj1.name = 'eric';
obj1.age = 20;
obj.show = function(){
console.log('我是obj1 的方法');
};
console.log(obj.name); // 输出:eric
console.log(obj.show()); //输出:我是obj1 的方法
// 创建对象2
var obj2 = {name: "eric", age: 20};
obj2.sex = '男';
console.log = obj2.name; //输出:{name: "eric", age: 20, sex: "男"}
// 创建对象3
var obj3 = {
name: 'eric',
age: 20,
show: function (val) {
console.log(val + '我是show 方法');
}
};
console.log(obj3.show('hello, ')); //输出:hello, 我是show 的方法
//对象内部方法调用内部方法
var obj4 = {
name: eric,
age: 20,
getName = function(){
console.log(obj4.name);
},
getInfo = function(){
obj4.getName();
}
}
console.log(obj4.getInfo()); //输出:eric
</script>
延长器:setTimeout(), setInterval(), clearInterval()
setTimeout
:只执行一次,setInterval
:可以执行多次,clearInterval
清除定时器
// setTimeout
setTimeout(function () {
console.log('我是定时器');
},3000)
function show(){
console.log('3秒后再执行我');
}
setTimeOut(show,3000);
// setinterval
setInterval(function(){
console.log(new Date());
},1000);
// 设定程序4秒后停止执行
var time = setInterval(function () {
console.log(new Date());
}, 1000);
setTimeout(function () {
clearInterval(time);
},4000);
发送验证码小案例
<button id="text">发送验证码</button>
<script>
var button = document.getElementById('text');
button.addEventListener('click',function () {
var text = document.getElementById('text').textContent;
var time = 6;
var val = setInterval(function () {
document.getElementById('text').textContent = time+'秒后重新发送';
time --;
if (time == 0){
clearInterval(val);
document.getElementById('text').textContent = text;
}
},1000);
});
</script>
THE END !