(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,共享方法
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的方法调用对象的方法,可以实现。
- -!不可能实现。prototype上的方法,是所有new出来的对象都共享。共享方法,只能访问(this.xxx)用this点出来的属性。私有属性本身是可以访问,但也随共享方法一起被共享了。不要去纠缠这个。