[H5]Javascript面向对象
JS中一切事物都是对象,对象具有封装和继承特性,类信息能够隐藏(包括属性与方法)。
/**
* 创建对象
*/
var city = {name:"chongqing",area:"8.24万平方千米",management:function () {
alert("nanagement")
}};
alert(city.name);
/**
* 使用函数构造器创建对象
*/
function CityObject (code) {
this._code = code;
}
// 使用原型链来指定
CityObject.prototype = {
name:"chongqing",
area:"8.24",
management:function () {
alert("management city"+this._code);
}
}
CityObject.prototype.population = "3075万";
var tempCity = new CityObject();
document.write("<br/>"+tempCity.name+","+tempCity.area+","+tempCity.population);
// 扩展,继承
function CountyObject (code) {
this._code = code;
}
CountyObject.prototype = new CityObject();
var superManage = CountyObject.prototype.management;
// 复写方法
CountyObject.prototype.management = function () {
// 调用父类中方法执行
superManage.call(this);
alert("management county"+this._code);
}
var tempCounty = new CountyObject("500000");
document.write("<br/>"+tempCounty.name+","+tempCounty.area+","+tempCounty.population);
tempCounty.management();
// 信息的隐藏,就是在方法中再套方法。
(function () {
var tempName = "";
function People () {
}
People.prototype.name = "gamin";
// 公开一个接口允许外部访问
window.People = People;
}());
(function () {
function Student () {
}
Student.prototype = new People();
var tempStu = new Student();
document.write("<br/>"+tempStu.name);
window.Student = Student;
}());
/**
* 创建对象的另一种方式
*/
(function () {
function Person (sex) {
var _this = {
name:"gamin",
age:"18"
};
_this.sex = sex;
_this.say = function () {
alert("ha ha"+_this.sex);
};
return _this;
}
window.Person = Person;
}());
(function () {
function Teacher (sex) {
var _this = Person(sex);
var superSay = _this.say;
// 复写父类中的方法
_this.say = function () {
superSay.call(_this);
alert("he he"+_this.sex);
}
return _this;
}
window.Teacher = Teacher;
}());
var tempTeacher = Teacher("man");
tempTeacher.say();
document.write("<br/>"+tempTeacher.age);