javascript面向?qū)ο?/h2>
初學(xué)javascript,感覺javascript的面向?qū)ο缶幊踢€是很有意思的,在此記錄下來.
面向?qū)ο蟮娜筇卣?封裝,繼承,多態(tài)
(多態(tài)還沒搞明白)
1.面向?qū)ο?定義一個(gè)對(duì)象
1.1:方式一,直接{ }
var Person = {
//properties
name:"myNmae",
age:12,
eat:function(){
console.log("I'm eating!");
}
}
//訪問
Person.name; //myNmae
Person.age; //12
Person.eat(); //"I'm eating"
1.2:方式二,函數(shù)構(gòu)造器,類似class的概念
//無參
function Person(){
}
Person.prototype = {
name:"myNmae",
age:12,
run:function(){
console.log("I'm running!");
}
}
//實(shí)例化
var p = new Person();
//訪問
p.name; //myName
p.age; //12
p.run(); //"I'm running!"
//有參數(shù)
function Person1(name){
this._name = name;
}
Person1.prototype = {
age : 13
}
2.javascript的繼承
function People(){
}
People.prototype.say = function(){
console.log("Hello!");
}
//Student繼承于People
function Student(){
}
Student.prototype = new People();
var stu = new Student();
stu.say(); //"Hello!"
3.重寫
function People(){
}
People.prototype.say = function(){
console.log("Hello!");
}
//Student繼承于People
function Student(){
}
Student.prototype = new People();
var superSay = Student.prototype.say;
Student.prototype.say = function(){
//調(diào)用父類的函數(shù)
superSay.call(this); //"Hello!"
console.log(" student say hello!");
}
var stu = new Student();
stu.say(); //"Hello!" + "student say hello!"
4.封裝,通過(function(){ //properties的模式 }());達(dá)到封裝
(function(){
var secret = "secret"; //外面不能直接訪問這個(gè)成員
function People(){
}
People.prototype.say = function(){
console.log("Hello!");
}
//對(duì)外接口
window.People = People;
}());
;
(function(){
//Student繼承于People
function Student(){
}
Student.prototype = new People();
var superSay = Student.prototype.say;
Student.prototype.say = function(){
//調(diào)用父類的函數(shù)
superSay.call(this); //"Hello!"
console.log(" student say hello!");
}
//對(duì)外的接口
window.Student = Student;
}());
var stu = new Student();
stu.say(); //"Hello!" + "student say hello!"
5.另外的一種寫法,面向?qū)ο?使用空對(duì)象承載成員信息
(function(){
function Person(){
_this = {};
_this.sayHello = function(){
alert("Hello");
}
return _this;
}
window.Person = Person;
}());
//繼承
(function(){
function Teacher(){
var _this = Person();
//重寫
var superSay = _this.sayHello;
_this.sayHello = function(){
superSay.call(_this);
alert("Haha!");
}
return _this;
}
window.Teacher = Teacher;
}());
var t = Teacher();
t.sayHello(); //"Hello" + "Haha!"