一、聲明對象的兩種常用形式
百度搜索 mdn JavaScript面向對象
https://developer.mozilla.org/zh-CN/docs/Learn/JavaScript/Objects/Object-oriented_JS
1,構造函數,形式
基本語法
// 定義對象構造器形式
function Method2() {
this.age = '20',
this.speak = function () {
console.log('翟浩浩測試');
}
}
new Method2().speak();
構造器形式傳參
// 定義對象構造器形式傳參
function Method3(name) {
this.name = name;
this.speak = function () {
console.log('執行方法' + name);
}
}
new Method3('zhnagfei').speak();
2,字面量形式
let zhh = {
//屬性
name: 'zhh',
age: '20',
//方法
method: function () {
console.log('這是方法');
}
}
//調屬性和方法
zhh.name;
zhh.method();
上面是es5,的常見寫法,es6有了一定的修改, 常見的如下
二、es5中對象調用屬性的兩種方法
對象.屬性名
對象['屬性名']
例如:
<script>
// 對象.屬性名
// 對象['屬性名']
function Person() {
this.name = 'zhh';
};
let person = new Person();
person.name;
person['name'];
console.log(person.name);
console.log(person['name']);
</script>
對象['屬性名'] 對於封裝函數非常重要,
對象.屬性名 是做不到的
例如:
<body>
<div id="div" style="width: 100px;height: 100px;background-color: crimson;"></div>
<script>
let div = document.getElementById('div');
let wdth = myStyle(div, 'width');
let height = myStyle(div, 'height');
console.log(wdth, height);
/*
* 對象['屬性名'] 對於封裝函數非常重要,
* 對象.屬性名 是做不到的
* eleObj 元素對象
* attr 屬性
*/
function myStyle(eleObj, attr) {
return eleObj.style[attr];
}
</script>
</body>
關於屬性的封裝可以參考:
https://blog.csdn.net/zhaihaohao1/article/details/102983531
三、es6對象的新寫法
1、屬性名的快速定義
let x =10;
let y =15;
let obj ={
x,y
}
console.log(obj);
// 上面的寫法等價於
let obj2 = {
x:x,
y:y
}
console.log(obj2);
// 上面的寫法等價於
let obj3 ={
x:20,
y:30
}
console.log(obj3);
2、修改的屬性名
let obj4 = {
age:'12',
['prop'+foo()]:'15'
}
function foo(){
return 12;
}
console.log(obj4);
// 對象的新寫法,對象中方法的快速定義
let obj5 = {
a:'我是a',
b:'我是b',
fangfa(){
console.log("測試方法5")
}
}
console.log(obj5.fangfa());
四、es6中class類的引入:
百度搜素 mdn class
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Classes
1、定義類,實例化對象,調用屬性和方法
// 引入class定義類和對象,和java一樣的語法
class Polygon {
// 構造方法,如果不寫,會默認一個無參數的構造方法
constructor(width) {
// this關鍵字指的是當前對象,作用域是這個類
// this.height 就是全局屬性,在外部可以直接用對象調用
this.width = width;
}
sayName() {
console.log('方法被調用'+this.width);
}
}
// 實例化對象
let polygon = new Polygon(100);
// 對象調屬性
console.log(polygon.width );
// 對象調方法
polygon.sayName();
2、在類裏面寫入set get 方法
// 在類裏面寫入set get 方法
// set get 是一個特殊的語法,向變量一樣賦值
class Square {
get area() {
return this.value;
}
set area(value) {
this.value = value;
}
}
// 實例化對象
let square = new Square();
// 調用 set 方法
square.width = 100;
// 調用 get 方法
console.log(square.width);
3、在類裏面寫入靜態方法,並調用
// 在類中寫入靜態方法
class Tiger {
static eat() {
console.log('老虎喜歡喫羚羊');
}
}
Tiger.eat();
4、extends繼承,重寫方法,super調父類方法
// 繼承
// 定義一個父類
class Person {
constructor() {
console.log();
}
// 名字
name() {
console.log('Person的方法');
}
}
// 定義一個子類
class Teacher extends Person {
constructor() {
// super 調用父類的構造方法
super();
}
// 重寫父類的方法
name() {
// 調用父類name方法
super.name();
console.log('Teacher的方法');
}
}
console.log(new Teacher('zhh').name());