js面向物件prototype
阿新 • • 發佈:2019-01-31
在JavaScript中,陣列、函式、正則表示式都是物件;而數字、字串和布林值則是物件中的構建,不可修改。
從廣義上來說,一個物件可以包含屬性,屬性被定義成鍵值對。例如:
var nothing = {};
var author = {
firstname:"C",
lastname:"Douglas",
book:{
title:"javaScript",
pages:"2000"
}
};
一般我們用點號的寫法獲取物件的屬性,author.firstname,author.book.title
如果試圖檢索一個不存在的屬性,可用小技巧console.log(author.age || “Not Found”)
基本引用到物件屬性的時候,會發生以下操作之一:
檢查物件是否擁有該屬性。如果有,則返回該屬性的值。
檢查與物件相關的原型。如果在其中找到了該屬性,則返回;否則返回undefined
//js的面向物件
function Player(){
// this.constructor.noOfPlayers++;
//私有屬性和函式,只能由特權方法瀏覽,編輯,呼叫
var age = 20;
var name = "c";
var available = true;
function isAvailable(){return available;}
//特權方法-可以從外部呼叫,也可以成員訪問
//特權方法和公共方法類似,但是可以訪問私有函式
this.getAge = function(){return age;}
this.userIsAvailable = function(){
if(isAvailable()){
return 'success';
}
}
this.setAge = function(age){
this.address = age;
return this.address;
}
//公共屬性,可以在任何地方修改
this.address = "american";
}
//公共方法-任何人都可讀取和寫入 只能訪問公共屬性和原型屬性
Player.prototype.switchAddress = function (){this.address="china";}
//原型屬性-任何人都可以讀取寫入
//原型屬性和公共屬性類似,優先讀取公共屬性中的內容
Player.prototype.address= "xxxxxxx"
//靜態屬性-任何人都可以讀取和寫入
// Player.noOfPlayers = 0;
var c = new Player();
alert(c.setAge(29))
js的繼承也和prototype有關係,採用原型鏈作為繼承的關鍵點。
function Person(){}
Person.prototype.cry = function(){
alert("cry");
}
function Child(){}
//繼承關係方式1
Child.prototype = new Person();
var aChild = new Child();
alert(aChild instanceof Child);
alert(aChild instanceof Person);
function Employee(){
this.name = '';
this.dept = 'None';
this.salary = '0.00';
}
Employee.prototype.age = 20;//如果想在執行時候修改屬性,儘量寫在外面
function Manager(){
Employee.call(this);//回撥函式,使用Employee的構造資訊
this.report = [];
}
//繼承關係方式2
Manager.prototype = Object.create(Employee.prototype);