// JavaScript Document
function className() {
//public属性
this.publicVar = "This is a public var.";
//private属性
var privateVar = "This is a private var.";
var instanceObj = this; //很关键,直到进入私有方法体前,在这里获得的this都是指向对象本身的
//private方法,不能由对象进行访问,这样就实现了私有方法
function privateFunction() {
document.write("This is a private function:");
document.write('<br/>');
document.write("publicVar = " + this.publicVar); //这里的this指代DOMwindow对象
document.write('<br/>');
document.write("privateVar = " + privateVar);
document.write('<br/>');
instanceObj.publicFunction(); //这样才能调用原型定义的public方法
}
//privileged方法,如果利用对象调用构造方法体内定义的方法的话,可以这样定义方法
this.privilegedFunction = function() {
document.write("This is a privileged function:");
document.write('<br/>');
document.write("publicVar = " + this.publicVar);
document.write('<br/>');
document.write("privateVar = " + privateVar);
document.write('<br/>');
}
}
//public方法
className.prototype.publicFunction = function() {
document.write("This is a public function:");
document.write('<br/>');
document.write("publicVar = " + this.publicVar);
document.write('<br/>');
document.write("privateVar = " + privateVar); //不能调用private属性,这样就实现了成员变量的封装
document.write('<br/>');
}
JS中关于作用域问题的实验
最新推荐文章于 2024-09-04 20:18:34 发布