zoukankan      html  css  js  c++  java
  • JavaScript——方法

    1、定义方法

    方法就是把函数放在对象的里面,对象只有两个东西 : 属性和方法

    var jjh = {
        name: '姜嘉航',
        bitrh: 1996,
        // 方法
        age: function () {
            // 今年 - 出生的年
            var now = new Date().getFullYear();
            return now-this.bitrh;
        }
    }
    //属性
    jjh.name  //姜嘉航
    //方法,一定要带  ()
    jjh.age() //24
    

    this.代表什么? 拆开上面的代码看看~

    function getAge() {
        // 今年 - 出生的年
        var now = new Date().getFullYear();
        return now-this.bitrh;
    }
    
    var jjh = {
        name: '姜嘉航',
        bitrh: 1996,
        age: getAge
    }
    
    jjh.age()   //24
    getAge()  NaN   window
    

    注意:this是无法指向的,是默认指向调用它的那个对象;

    2、apply

    在javascript中可以控制 this 指向!

    function getAge() {
        // 今年 - 出生的年
        var now = new Date().getFullYear();
        return now-this.bitrh;
    }
    
    var jjh= {
        name: '姜嘉航',
        bitrh: 1996,
        age: getAge
    };
    
    var xiaoming = {
        name: '小明',
        bitrh: 2000,
        age: getAge
    };
    
    jjh.age() //24
    
    getAge.apply(xiaoming,[]);// this,指向了 xiaoming,参数为空
    
  • 相关阅读:
    BZOJ3669
    HDU3726
    BZOJ3282
    BZOJ2843
    Link/cut Tree
    Codeforces396A
    LOJ6277~6285 数列分块入门
    Codeforces446C
    Codeforces475D
    Codeforces103D
  • 原文地址:https://www.cnblogs.com/godles/p/12196425.html
Copyright © 2011-2022 走看看