JS实例属性/方法、静态属性/方法、私有属性/方法、原型属性/方

2020-01-10  本文已影响0人  David_Rao

实例属性/方法 & 静态属性/方法

<script>
    function Person(name, age, doFunc) {
        // 实例属性和方法
        this.name = name;
        this.age = age;
        this.doFunc = doFunc;
        if(!Person.personCount){
            Person.personCount = 0;  // 静态属性
        }
        Person.personCount++;
    }

    // 静态方法
    Person.printPersonCount = function () {
        console.log('总共创建了' + Person.personCount + '个人');
    };

    var p1 = new Person('张三', 18, function () {
        console.log("大家好我是张三");
    });

    var p2 = new Person('李四', 18, function () {
        console.log("大家好我是李四");
    });

    Person.printPersonCount();
</script>

私有属性/方法

对象外部无法访问

<script>
    function Caculator() {
        // 1. 私有属性
        var result = 0;
        // 2. 私有方法
        function checkNum(num) {
            var isNum = typeof num === 'number';
            if(!isNum){
                alert('输入有误');
            }
            return isNum;
        }

        this.add = function (num) {
            if(checkNum(num)){
                result += num;
            }
            return this;
        };
        this.minus = function (num) {
            if(checkNum(num)){
                result -= num;
            }
            return this;
        };
        this.logResult = function () {
            console.log(result);
            return this;
        };
        this.cleanResult = function () {
            result = 0;
            return this;
        }
    }

    var c = new Caculator();
    c.add(2).add(3).minus(1);
    c.logResult();  // 4
    console.log(c);
    console.log(c.result);  // undefined
</script>

原型属性/方法

实例属性/方法是被所有对象所共用的,所以无所谓的实例、静态、私有的说法

<script>
    function Person(options) {
        this._init(options);  // 调用原型方法
    }
    Person.prototype = {
        ID: '001',  // 原型属性
        _init: function (options) {  // 原型方法
            this.name = options.name;  // 实例属性
            this.age = options.age;  // 实例属性
            this.gender = options.gender;  // 实例属性
            this.run = function () {  // 实例方法
                console.log(this.name + '会跑');
            }
        },
        eat: function () {  // 原型方法
            console.log(this.name + '会吃');
        }
    };
    Person.prototype.fly = function () {  // 原型方法
        console.log(this.name + '会飞');
    };
    Person.prototype.hobby = 'Basketball';  // 原型属性

    var david = new Person({'name': 'David', 'age': 18, 'gender': '男'});

    console.log(david.ID);
    console.log('name:', david.name, ',age:', david.age, ',gender:', david.gender, ',hobby:', david.hobby);
    david.eat();
    david.run();
    david.fly();
</script>
上一篇 下一篇

猜你喜欢

热点阅读