利用 this 实现的公共方法中可以访问类的私有成员(用 var 声明的变量),私有方法(用 function 直接定义的方法);
利用原型扩展实现的方法中,无法调用私有成员和变量。
例子如下所示(把其中注释掉的两行恢复就可以看到区别):

使用 this 指针和 prototype 实现 js 的 OO 时的一个区别function T(name) {
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别    
this.Name = name;
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别    
var x = 5;
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别    
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别    
function privateFunc() {
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别        alert('
in private method: do sometheing');
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别    }
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别    
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别    
this.PublicFunc = function() {
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别        
// 可以调用私有方法,访问私有成员变量。
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别
        privateFunc();
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别        alert('x 
= ' + x);
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别        alert('
in public method: do something else.');
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别    }
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别}
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别
//var t = new T('t1');
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别//
t.PublicFunc();
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别

使用 this 指针和 prototype 实现 js 的 OO 时的一个区别T.prototype.PublicFunc2 
= function() {
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别    alert('
in public method 2.');
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别    
// 下面两行都会出错。在利用 prototype 扩展的方法里无法调用对象的私有方法,也访问不到通过 var 定义的私有成员。
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别
    // alert(x);
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别
    // privateFunc();
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别
}
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别
var t2 = new T('t2');
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别t2.PublicFunc();
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别t2.PublicFunc2();
使用 this 指针和 prototype 实现 js 的 OO 时的一个区别

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-20
  • 2022-01-10
  • 2021-10-18
  • 2021-12-04
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-14
相关资源
相似解决方案