工厂函数
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>工厂函数</title>
</head>
<body>
<script>
function person(name,age,hobby){
var obj = {};//需要新建对象
obj.name = name;
obj.age = age;
obj.hobby = hobby;
return obj;//需要返回对象
}
var huixin = person("huixin",21,["swim","game"]);
var xiaojuju = person("xiaojuju",21,["smell","travel"]);
console.log(huixin);
console.log(xiaojuju);
//this指向window
</script>
</body>
</html>
构造函数
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>工厂函数</title>
</head>
<body>
<script>
function person(name,age,hobby){
//var obj = {};省略 自动生成
this.name = name;
this.age = age;
this.hobby = hobby;
//return obj;省略 自动返回
}
var huixin = new person("huixin",21,["swim","game"]);//要new一下
var xiaojuju = new person("xiaojuju",21,["smell","travel"]);
console.log(huixin);
console.log(xiaojuju);
//this指向改变
</script>
</body>
</html>
this是根据调用者来决定指向,如果obj调用就是指向obj,如果是window就是指向window
回调函数
用document.write时候骑自行车去游泳会消失,不消失用这个解决
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>practice2</title>
</head>
<style>
*{list-style: none;}
</style>
<body>
<ul id="ul1">
</ul>
<script>
var ul1 = document.getElementById("ul1");
ul1.innerHTML += "<li>"+"骑车去游泳"+"</li>"
setInterval(function(){
ul1.innerHTML += "<li>"+"买票换衣"+"</li>"
ul1.innerHTML += "<li>"+"跳水游泳"+"</li>"
},3000)
</script>
</body>
</html>
第一步
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>practice2</title>
</head>
<body>
<script>
console.log("骑车去游泳<br/>");
setInterval(function(){
console.log("买票换衣<br/>");
console.log("跳水游泳<br/>");
},3000)
</script>
</body>
</html>
第二步
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>practice2</title>
</head>
<body>
<script>
console.log("骑车去游泳<br/>");
setInterval(function(){
console.log("买票换衣<br/>");
function swim(){
console.log("跳水游泳<br/>");
}
swim()//把第三句变函数
},3000)
</script>
</body>
</html>
第三步
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>practice2</title>
</head>
<body>
<script>
console.log("骑车去游泳");
setInterval(function() {
console.log("买票换衣");
(function() {
console.log("跳水游泳");
})() //去掉函数名,自执行
}, 3000)
</script>
</body>
</html>
第四步
!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>practice2</title>
</head>
<body>
<script>
console.log("骑车去游泳");
function swimming() {
setInterval(function() {
console.log("买票换衣");
(function() {
console.log("跳水游泳");
})()
}, 3000)
}//在外面再加一个函数
</script>
</body>
</html>
第五步 调回函数
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>practice2</title>
</head>
<body>
<script>
console.log("骑车去游泳");
function swimming(back) {
this.name = "huixin";
setTimeout(function() {
console.log("买票换衣");
back()
}, 3000)
}
var obj = new swimming(function() {
console.log("跳水游泳");
});
swimming(function() {
console.log("111");})
</script>
</body>
</html>