您的位置:首页 > Web前端 > JavaScript

21-JavaScript-面向对象-对象的属性和方法以及this

2013-11-12 10:56 786 查看
- 对象的属性(私有/公有)

- 对象的方法(私有/公有)

- this

0. 语法

function ClassName() {
    
    var variableName1;  // 私有属性
    
    this.variableName2; // 公有属性

    function func1() {  // 私有方法
        // do something
    }

    this.func2 = function() {   // 公有方法
        // do something
    }

}


1. 为什么需要 this

当实例化一个对象后,该对象自动拥有某些属性.

1) this 修饰类的 属性/方法

则 该 属性/方法 是 公有的

2) this 修饰私有方法内的变量

则 this代表 调用该私有方法的实例

2. 引入

function Student() {
        this.number = "A001";   // 公有属性
        this.name = "张三";   
    }

    var stu1 = new Student();

    console.info( stu1.number ); // A001
    console.info( stu1.name );   // 张三


3. 私有属性 与 公有方法(特权方法)

function Student() {
        
        var name = "李四";    // 私有属性

        this.getName = function() { // 公有方法
            return name;
        }

    }

    var stu = new Student();

    console.info( stu.name );   // undefined
    console.info( stu.getName() );  // 李四


4. 私有方法 内部使用

function Student() {
        
        var name = "王五";    // 私有属性

        function setNickname(name) {    // 私有方法
            return this.name = name;
        }

        this.getName = function() {     // 公有方法
            return setNickname( "X" + name + "X" );
        }

    }

    var stu = new Student();

    // TypeError: stu.setNickname is not a function
    // console.info( stu.setNickname() ); 
    
    console.info( stu.getName() ); // X王五X


5. this 代表谁

this代表调用者.

this只能在类的方法中使用

1) 示例1

this代表Student的实例

function Student() {
        this.getName = function() {
            return this.name;
        }
    }

    var stu = new Student();

    stu.name = "赵六";
    console.info( stu.getName() );  // 赵六


2) 示例2

this代表window对象

function showValue() {
        return this.value;
    }

    var value = 123;
    // <==> window.value = 123;
    // <==> this.value = 123;

    console.info( showValue() );    // 123
    // <==> console.info( window.showValue() );
    // <==> console.info( this.showValue() );
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐