+ -
当前位置:首页 → 问答吧 → js的对象,如何实现方法共享,数据分离?

js的对象,如何实现方法共享,数据分离?

时间:2011-12-05

来源:互联网

JScript code

(function(){
    function Person(firstName, lastName, age){ 
        //私有变量: 
        var _firstName = firstName; 
        var _lastName = lastName; 
 
        //公共变量: 
        this.age = age; 
 
        //方法: 
        this.getName = function() { 
            return (firstName + " " + lastName); 
        }; 
        Person.prototype.sayHello = function() { 
            return ("我是" + firstName + " " + lastName); 
        }; 

        var f = function(){
            return _firstName;
        };
        Person.prototype.get = function() { 
            return f;
        }; 
    }; 
     
    var gs = new Person("Bill", "Gates", 53); 
    var jb = new Person("Steve", "Jobs", 53); 
    
    document.write("<br>getName:");
    document.write(gs.getName() + "=" + jb.getName());//结果是正确的,数据分离了,但方法也分离了

    document.write("<br>sayHello:");  
    document.write(gs.sayHello()  + "=" + jb.sayHello()); //结果有问题,都是Jobs了,主要是方法共享引起,数据只认最后一次,这是与getName()的方法区别

    document.write("<br>方法:"); 
    document.write(gs.getName ==  jb.getName); //这是false,每个对象各自的方法
    document.write(","); 
    document.write(gs.sayHello == jb.sayHello); //这是true,共享方法


作者: WxmJun   发布时间: 2011-12-05


JScript code
    function Person(firstName, lastName, age){ 
        //私有变量: 
        var _firstName = firstName; 
        var _lastName = lastName; 
        
        //公共变量: 
        this.age = age; 
    
        //方法: 
        this.getName = function(){ 
            return firstName + " " + lastName;
        }; 
        this.getFirstName = function(){
            return _firstName;
        };
    }; 

    Person.prototype.get = function() { 
        return this.getFirstName();
    }; 
    
    Person.prototype.sayHello = function() { 
    


prototype的方法就是共享的,用prototype的方法调用对象的方法,可以实现。

作者: zswang   发布时间: 2011-12-06