1. ES5的聲明方法
function Person() {
var name = 'abby'; // 私有屬性
function getName() { // 私有方法
console.log(this, name, this.age); // this==>window
}
this.age = 10; // 公有屬性
this.speak = function() { // 特權(quán)方法
console.log(this, name, this.age); // this==>person (實例對象)
return getName;
}
}
Person.sex = '女'; // 靜態(tài)屬性
Person.prototype.country= 'China'; // 原型屬性
Person.walk = function() { // 靜態(tài)方法
console.log('walk==>', this); // this==> 指向Person類
}
Person.prototype.sleep = function() { // 公有方法
console.log('sleep==>', this); // this ==> person (實例對象)
}
const person = new Person();
(person.speak())();
const getName = person.speak();
getName();
console.log(Person.sex);
console.log(Person.prototype.country);
Person.walk();
person.sleep();
2. ES6的聲明方法
class Person() {
static sex = '女'; // 靜態(tài)屬性 提案用#表示私有屬性 #sex = '女';
constructor() {
this.age = 10; // 公有屬性
}
age = 10; // 等同與在構(gòu)造函數(shù)中this.age = 10;
this.age = 10; // 等價上面
static walk() { // 靜態(tài)方法
console.log('walk==>', this);
}
sleep() { // 原型方法
console.log('sleep==>', this);
} // 等同 Person.prototype.sleep
get name() {
console.log('獲取name屬性');
}
set name() {
console.log('設(shè)置name屬性');
}
}
// Class 無法實現(xiàn)真正意義上的私有屬性,或者用Symbol,可以自己百度看看實現(xiàn)方式
const person = new Person();
person.name = 'abby'; // 設(shè)置name屬性
console.log(person.name); // 獲取name屬性
3. 調(diào)用
var name = 'abby'; // 私有屬性
// 在對象內(nèi)部使用'var'關(guān)鍵字來聲明,且只能被私有函數(shù)和特權(quán)方法訪問
this.age = 10; // 共有屬性
// 在通過實例對象調(diào)用,不能被私有函數(shù)所調(diào)用
function getName() { // 私有方法
console.log(this, name, this.age); // this==>window
}
var functionName = function() {}
// 能被特權(quán)方法調(diào)用(包括對象的構(gòu)造函數(shù))和私有方法調(diào)用
this.speak = function(){...}
// 1. this.特權(quán)方法() 方式來調(diào)用特權(quán)函數(shù) 2. 私有方法()方式來調(diào)用私有函數(shù)。
Person.prototype.sleep=function(){...}
// 實例對象調(diào)用
Person.prototype.contry = ''china;
// 同過實例對象調(diào)用或者ClassName.prototype.propertyName調(diào)用
Person.sex = '女';
// 不會被實例繼承,只能類調(diào)用ClassName.propertyName
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。