标签:代码 png str sch body var fence utf-8 return
方法就是把函数写在对象的里面。
对象中只有两个东西:属性和方法。
完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript学习</title>
<script>
‘use strict‘;
var school = {
name: "DongDa",
num: 20,
age: function () {
return this.num;
}
}
console.log(school.name);
console.log(school.age());
</script>
</head>
<body>
</body>
</html>
1.1中采用this指针来指向当前对象。而1.2中,函数和对象分开写,需要采用apply将函数指向特定的对象。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript学习</title>
<script>
‘use strict‘;
function getAge() {
return this.num;
}
var school = {
name: "DongDa",
num: 20,
age: getAge
};
var age = getAge.apply(school,[]); //[]是由于参数为空
console.log(age);
</script>
</head>
<body>
</body>
</html>
标签:代码 png str sch body var fence utf-8 return
原文地址:https://www.cnblogs.com/WZ-BeiHang/p/12335500.html