+ -
当前位置:首页 → 问答吧 → 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()); //结果有问题,都是“Steve 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

补充一下,不能把这些变量公开 _firstName ,_lastName ,它们必须是私有的

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

JScript code
this.sayHello = function(a,b) {
            return function() {
                return ("我是" + a + " " + b)
            };
        }(firstName,lastName);

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

楼上的JScript code
document.write(gs.sayHello == jb.sayHello);
是false哦,我想要是true
JScript code


//上面方法的代码可能变量用错了,可能有误导: 
        this.getName = function() { 
            return (_firstName + " " + _lastName + ":" + this.age); 
        }; 
        Person.prototype.sayHello = function() { 
            return ("我是" + _firstName + " " + _lastName + ":" + this.age); 
        }; 

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

JScript code
Person.prototype.sayHello = function() {
            return function() {
                return ("我是" + this.getName())
            };
        }();

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

JScript code
Person.prototype.sayHello = function() {
            return ("我是" + this.getName())
        };

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

是不是可以这样理解:

把有的闭包变量,必须通过闭包方法引用? 不能使用prototype方法引用?

prototype方法要使用闭包变量,必须通过this.get方法获取,不能直接使用?

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

prototype方法中的this指向的是调用这个方法的对象,而这两个对象的getName方法访问的变量又不相同

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