22-JavaScript-面向对象-构造函数-prototype

来源:互联网 发布:jdk 7u3 windows i586 编辑:程序博客网 时间:2024/05/22 01:34
- 构造函数
- 成员函数
- prototype

1. 成员函数 的介绍


    小明 -->  人的实例

     属性: 身高 体重 ...
     行为: 吃饭 睡觉 唱歌 ... 

    成员函数就是用来描述对象的行为的

2. 构造函数 -- 描述 小明

    function Person(name, height, weight) {                this.name = name;        this.height = height;        this.weight = weight;        this.show = function() {            return this.name + "  " + this.height + "  " + this.weight;        }        this.eat = function(food) {            return this.name + " is eating " + food;        }        this.sleep = function() {            return this.name + " like sleeping!";        }        this.sing = function(song) {            return this.name + " like singing " + song;        }    }    var p = new Person("小明", "170cm", "50kg");    console.info( p.show() );    console.info( p.eat( "apple" ) );    console.info( p.sleep() );    console.info( p.sing( "哇哈哈" ) );


3. 注


    ①每个Person类的实例, 都会有各自的 eat() sleep() 函数代码
        对实例属性和方法的改变, 不会影响到其他的实例.
        但, 这会造成内存的额外消耗. 如图

    ②可以使用 "==", 判断对象的方法的地址是否相等
    
    ③可使用原型的方式来使每个实例共享函数代码.

4. 给单独对象追加方法


    function Person() {
    }

 1) 方式一

    function func() {        // do something    }        var p = new Person();    p.show = func;

 2) 方式二

    var p = new Person();    p.show = function() {        // do something    };  

 3) 对象间互不影响

    function Person() {        this.name = "123";    }    var p1 = new Person();    var p2 = new Person();    console.info( p1.name );    // 123    console.info( p2.name );    // 123    p1.name = "AAA";    console.info( p1.name );    // AAA    console.info( p2.name );    // 123    var p3 = new Person();          console.info( p3.name );    // 123 


5. 让所有对象共享同一个函数 -- prototype


 1) 说明


    prototype, 相当于Java的static, 
    修饰的属性/方法是属于类的.

 2) 语法


    ClassName.prototype.propertyName = propertyValue;

    ClassName.prototype.methodName = method;

 3) 举例

    function Dog() {                this.eat = function() {            return "a dog is eating!";        };        Dog.prototype.bark = function() {            return "a dog is singing!!!";        };    }    var d1 = new Dog();    var d2 = new Dog();    console.info( d1.eat == d2.eat );   // false    console.info( d1.bark == d2.bark ); // true    console.info( d1.bark() );    console.info( d2.bark() );    // 更改模板    Dog.prototype.bark = function() {        return "heihei, I'm a Cat!!!!!!"    }    console.info( d1.bark() );    console.info( d2.bark() );    // false    // true    // a dog is singing!!!    // a dog is singing!!!    // heihei, I'm a Cat!!!!!!    // heihei, I'm a Cat!!!!!!