// 在对象中
var Restaurant = {
name: 'McDonald',
// 公有方法
getName: function() {
return this.name;
}
}
// 在构造函数中
function Person(name, age) {
this.name = name;
this.age = age;
// 公有方法
this.getName = function() {
return this.name;
}
}
// 在原型中
Person.prototype.getAge = function() {
return this.age;
}
var yourObject = (function() {
// 私有属性和方法
return {
// 公有方法和属性
}
}) ();
var Restaurant = (function() {
// 私有属性
var _total = 10;
// 私有方法
var _buyFood = function() {
_total--;
};
var _getTotal = function() {
return _total;
}
return {
name: 'McDonald',
getTotal: _getTotal,
buy: _buyFood
}
}) ();
Restaurant.buy();
console.log(Restaurant.name); // 'McDonald'
console.log(Restaurant.getTotal()); // 9
function Restaurant(name) {
// 私有属性
var _total = 10;
// 公有属性
this.name = name;
// 私有方法
function _buyFood() {
_total--;
}
// 特权方法
this.buy = function() {
_buyFood();
}
this.getTotal = function() {
return _total;
}
}
// 公有方法, 注意这里不能访问私有成员_total
Restaurant.prototype.getName = function() {
console.log(_total); // Uncaught ReferenceError: _total is not defined
return this.name;
}
var McDonald = new Restaurant('McDonald');
console.log(McDonald.getName()); // 'McDonald'
McDonald.buy();
console.log(McDonald.getTotal()); // 9
var Restaurant = (function() {
// 私有属性
var _total = 10;
// 私有方法
function _buyFood() {
_total--;
}
// 构造函数
function restaurant(name) {
this.name = name;
this.getTotal = function() {
return _total;
}
}
restaurant.prototype.buy = function() {
console.log(_total); // 10
_buyFood();
}
restaurant.prototype.getName = function() {
return this.name;
}
return restaurant;
}) ();
var McDonald = new Restaurant('McDonald');
console.log(McDonald.getName()); // 'McDonald'
McDonald.buy();
console.log(McDonald.getTotal()); // 9
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有