JavaScript的方法

JavaScript的方法

方法就是把函数写在对象的里面。

对象中只有两个东西:属性和方法。

1. 方法的写法和调用

1.1. 方法的第一种写法(直接把函数写在对象中)

完整代码如下:

<!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.2. 方法的第二种写法(函数写在对象外面,对象中调用函数),此时,需要使用apply(),来指向对象。

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>

 

 

猜你喜欢

转载自www.cnblogs.com/WZ-BeiHang/p/12335500.html
今日推荐