1. ES5的声明方法
function Person() {
var name = 'abby'; // 私有属性
function getName() { // 私有方法
console.log(this, name, this.age); // this==>window
}
this.age = 10; // 公有属性
this.speak = function() { // 特权方法
console.log(this, name, this.age); // this==>person (实例对象)
return getName;
}
}
Person.sex = '女'; // 静态属性
Person.prototype.country= 'China'; // 原型属性
Person.walk = function() { // 静态方法
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 = '女'; // 静态属性 提案用#表示私有属性 #sex = '女';
constructor() {
this.age = 10; // 公有属性
}
age = 10; // 等同与在构造函数中this.age = 10;
this.age = 10; // 等价上面
static walk() { // 静态方法
console.log('walk==>', this);
}
sleep() { // 原型方法
console.log('sleep==>', this);
} // 等同 Person.prototype.sleep
get name() {
console.log('获取name属性');
}
set name() {
console.log('设置name属性');
}
}
// Class 无法实现真正意义上的私有属性,或者用Symbol,可以自己百度看看实现方式
const person = new Person();
person.name = 'abby'; // 设置name属性
console.log(person.name); // 获取name属性
3. 调用
var name = 'abby'; // 私有属性
// 在对象内部使用'var'关键字来声明,且只能被私有函数和特权方法访问
this.age = 10; // 共有属性
// 在通过实例对象调用,不能被私有函数所调用
function getName() { // 私有方法
console.log(this, name, this.age); // this==>window
}
var functionName = function() {}
// 能被特权方法调用(包括对象的构造函数)和私有方法调用
this.speak = function(){...}
// 1. this.特权方法() 方式来调用特权函数 2. 私有方法()方式来调用私有函数。
Person.prototype.sleep=function(){...}
// 实例对象调用
Person.prototype.contry = ''china;
// 同过实例对象调用或者ClassName.prototype.propertyName调用
Person.sex = '女';
// 不会被实例继承,只能类调用ClassName.propertyName
网友评论