javascript中公有方法和私有方法是什么
时间:2022-02-23 17:37
在javascript中,公有方法是指能被外部访问并调用的方法;而私有方法是指在对象的构造函数里声明,外部不可见且不可访问的方法。 本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。 一:公有方法 公有方法就是能被外部访问并调用的方法 二:私有方法和公有方法 特权方法是指有权访问内部私有属性和私有方法的公有方法(能够访问私有方法,私有属性的方法叫特权方法,也是公有方法的一种) 私有方法是指在对象的构造函数里声明,外部不可见且不可访问的方法。 使用不同方式定义私有方法和特权方法的形式不同 在对象中我们通过Object对象表达式来创建一个对象并添加一些属性和方法,然后直接采用静态的方式调用。如Rest.getName(); 立即执行函数对象的私有数据放置在一个匿名函数立即执行表达式(IIFE)中,这意味着这个函数只存在于被调用的瞬间,一旦执行后就立即被销毁了 这里和前面的定义Rest一样啊,可以通过yourObject直接的访问。这样的模块化的访问还是比较的厉害的。 使用了闭包的方式来间接使用内部私有变量 构造函数中定义私有属性和方法很方便,我们不需要使用闭包,可以在调用的时候初始化数据 结合使用 使用构造函数方式可以传入一些初始化的数据,但在公有方法中无法访问到私有成员属性,如果有很多公有方法需要访问私有数据,我们全部用特权方法来写,最后会给每个实例带去很多没有必要的方法。 【相关推荐:javascript学习教程】 以上就是javascript中公有方法和私有方法是什么的详细内容,更多请关注gxlsystem.com其它相关文章!// 对象中
var test1 = {
name:'大白',
getName:function(){
console.log(this.name);
}
}
//调用
test1.getName();//大白
// 构造函数中
function test2(name,age){
this.name = name;
this.age = age;
//公有方法
this.getName = function(){
console.log(this.name);
}
}
// 在原型中
test2.prototype.getAge = function(){
console.log(this.age);
}
//调用
var test3 = new test2('小白',12);
test3.getName();//小白
test3.getAge();//12
var yourObject = (function() {
// 私有属性和方法
return {
// 公有方法和属性
}
}) ();
var test4 = (function(){
//私有属性
var total = 10;
// 私有方法
var buy = function(){
total--;
}
var get = function(){
return total;
}
return {
name:'小白白',
getTotal:get,//使用了闭包的方式来简介使用内部私有变量
buyfood:buy
}
})();
test4.buyfood();
console.log(test4.name);//小白白
console.log(test4.getTotal());//9
// 构造函数中
function test5(name) {
// 私有属性
var total = 10;
// 公有属性
this.name = name;
// 私有方法
function _buyFood() {
total--;
}
// 特权方法,才能访问私有的属性和私有的方法
this.buy = function() {
_buyFood();
}
this.getTotal = function() {
return total;
}
}
// 公有方法, 注意这里不能访问私有成员_total
test5.prototype.getName = function() {
//console.log(_total); // Uncaught ReferenceError: _total is not defined
return this.name;
}
var test6 = new test5('大小白');
console.log(test6.getName()); // '大小白'
test6.buy();
console.log(test6.getTotal()); // 9
var test7 = (function(){
// 私有属性
var total = 10;
// 私有方法
function buyFood(){
total--;
}
// 构造函数
function test7(name){
this.name = name;
this.getTotal = function(){
return total;
}
}
// 公有方法 这里不是test7内部的私有
test7.prototype.buy = function(){
console.log(total);
buyFood();
}
test7.prototype.getName = function(){
return this.name;
}
return test7;
})();
var test0 = new test7('大大白');
console.log(test0.getName());//大大白
test0.buy();//10
console.log(test0.getTotal());//9