CMAScript 2015(ES6)引入了JavaScript類的概念,增強了面向對象的語言特性。
類定義
通過class關鍵字來定義一個類。
class MyClass { }
類繼承
通過extends關鍵字來繼承一個父類。
class MyClass extends MyFatherClass { }
構造函數
類可以包含一個名為constructor的構造函數,該方法在實例化類對象的時候會被調用。一個類只能有一個構造函數,出現多個constructor會報錯。如果沒有定義構造函數,會添加默認的構造函數。
class MyClass { constructor() { } }
如果繼承了父類,可以在構造函數中使用super()來調用父類的構造函數。另外如果在構造函數中使用了this關鍵字,需要在使用this之前首先調用super();
class MyClass extends MyFatherClass { constructor(x) { super(); this.x=x; } }
方法定義
class MyClass { // 方法1 method1() { } // 方法2 method2(x, y) { } }
普通方法需要通過類實例對象來調用。
const my=new MyClass(); my.method1();
使用static關鍵字來定義一個靜態方法。
class MyClass { static doSomething() { } }
調用靜態方法不需要實例化該類,不能通過一個類實例調用靜態方法。
MyClass.doSomething();
class MyClass { get name() { } set name(name) { this.name=name; } }
getter和setter方法調用方式:
const my=new MyClass(); // getter調用 const name=my.name; // setter調用 my.name='John';
成員變量
和其他靜態語言如Java不一樣的是,JavaScript的成員變量不需要定義,在類內部直接通過this.xxx來調用就可以。
、認識DOM對象模型
DOM:Document Object Model(文檔對象模型)
節點與節點的關系
1、訪問節點,使用getElement系列方法訪問指定節點
getElementById()、 getElementsByName()、
getElementsByTagName();
2、根據層次關系訪問節點:
屬性名稱 描述
parentNode 返回節點的父節點
childNodes 返回子節點集合,childNodes[i]
firstChild 返回節點的第一個子節點,最普遍的用法是訪問該元素的文本節點
lastChild 返回節點的最后一個子節點
nextSibling 下一個節點
previousSibling 上一個節點
elment屬性:
屬性名稱 描述
firstElementChild 返回節點的第一個子節點,最普遍的用法是訪問該元素的文本節點
lastElementChild 返回節點的最后一個子節點
nextElementSibling 下一個節點
previousElementSibling 上一個節點
節點信息表示:
nodeName:節點名稱
nodeValue:節點值
nodeType:節點類型
操作節點的屬性:
getAttribute("屬性名")
setAttribute("屬性名","屬性值")
創建和插入節點:
名稱 描述
createElement( tagName)創建一個標簽名為tagName的新元素節點
A.appendChild( B)把B節點追加至A節點的末尾
insertBefore( A,B )把A節點插入到B節點之前
cloneNode(boolean)復制(克隆)某個指定的節點
刪除和替換節點:
名稱描述
removeChild( node)刪除指定的節點
replaceChild( newNode, oldNode)屬性attr 用其他的節點替換指定的節點
操作節點樣式:
改變樣式的屬性
style屬性
HTML元素.style.樣式屬性="值";
className屬性
HTML元素.className="樣式名稱";
二、示例展示
1.輪播圖示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>輪播圖顯示</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
#outer {
width: 300px;
margin: 50px auto;
padding: 10px;
background-color: greenyellow;
text-align: center;
}
#outer>img {
width: 300px;
height: 300px;
}
</style>
<script>
window.onload=function () {
// 點擊按鈕切換圖片
var prev=document.getElementById("prev");
var next=document.getElementById("next");
// 要切換圖片就要修改img標簽的src屬性
var img=document.getElementsByTagName("img")[0];
var imgArr=["img/tou01.jpg", "img/tou02.jpg", "img/tou03.jpg", "img/tou04.jpg"];
// 創建一個變量,來保存當前正在顯示的圖片的索引
var index=0;
// 設置提示文字
var info=document.getElementById("info");
// 分別為兩個按鈕綁定單機響應函數 上一張函數
prev.onclick=function () {
index--;
// 判斷index是否小于0
if (index < 0) {
index=imgArr.length-1;
}
img.src=imgArr[index];
info.innerHTML="共"+imgArr.length+"張圖片"+"當前是第"+(index+1)+"張";
}
// 下一張函數
next.onclick=function () {
index++;
if (index > imgArr.length - 1) {
index=0;
}
img.src=imgArr[index];
// 當我在點擊按鈕以后在重新執行一遍
info.innerHTML="一共"+imgArr.length+"張圖片"+"當前是第"+(index+1)+"張";
}
}
</script>
<body>
<div id="outer">
<p id="info">一共4張圖片當前是第1張</p>
<img src="img/tou01.jpg" alt="" />
<button id="prev"><上一張</button>
<button id="next">下一張></button>
</div>
</body>
</html>
2.論壇發帖示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>制作課工場論壇發貼</title>
</head>
<style>
*{margin: 0; padding: 0; font-family: "Arial", "微軟雅黑";}
ul,li{list-style: none;}
.bbs{margin: 0 auto; width: 600px; position: relative;}
header{padding: 5px 0; border-bottom: 1px solid #cecece;}
header span{display:inline-block; width: 220px; height: 50px; color: #fff; background: #009966; font-size: 18px; font-weight: bold; text-align: center;line-height: 50px; border-radius: 8px; cursor: pointer;}
.post{position: absolute; background: #ffffff; border: 1px #cccccc solid; width: 500px; left: 65px; top:70px; padding: 10px; font-size: 14px; z-index: 999999; display: none;}
.post .title{width: 450px; height:30px; line-height: 30px; display: block; border: 1px #cecece solid; margin-bottom: 10px;}
.post select{width: 200px; height: 30px;}
.post .content{width: 450px; height: 200px; display: block; margin: 10px 0;border: 1px #cecece solid;}
.post .btn{width: 160px; height: 35px; color: #fff; background: #009966; border: none; font-size: 14px; font-weight: bold; text-align: center; line-height: 35px; border-radius: 8px; cursor: pointer;}
.bbs section ul li{padding: 10px 0; border-bottom: 1px #999999 dashed;
overflow: hidden;}
.bbs section ul li div{float: left; width: 60px; margin-right: 10px;}
.bbs section ul li div img{ border-radius:50%; width: 60px;}
.bbs section ul li h1{float: left; width: 520px; font-size: 16px; line-height: 35px;}
.bbs section ul li p{color: #666666; line-height: 25px; font-size: 12px; }
.bbs section ul li p span{padding-right:20px;}
</style>
<body>
<div class="bbs">
<header><span onclick="showDiv();">我要發帖</span></header>
<section>
<ul id="showContent"></ul>
</section>
<div class="post" id="showSubmit">
<input class="title" placeholder="請輸入標題(1-50個字符)" id="title">所屬版塊:
<select id="section">
<option>請選擇版塊</option>
<option value="電子書籍">電子書籍</option>
<option value="新課來了">新課來了</option>
<option value="新手報到">新手報到</option>
<option value="職業規劃">職業規劃</option>
</select>
<textarea class="content" id="content"></textarea>
<input class="btn" value="發布" onclick="publish();">
</div>
</div>
</body>
<script src="js/bbs.js"></script>
</html>
// 全局對象
var imgs=new Array("tou01.jpg", "tou02.jpg", "tou03.jpg", "tou04.jpg");
// 顯示發帖div
function showDiv() {
document.getElementById("showSubmit").style.display="block";
}
// 點擊發布添加內容到Li
function publish() {
// 獲得隨機頭像的數組下標
var index=Math.floor(Math.random() * 4);
// 創建li節點
var tvLi=document.createElement("li");
// 創建div節點
var tvDiv=document.createElement("div");
// 創建img圖片節點
var tvImg=document.createElement("img");
// 設置圖片節點src屬性
tvImg.setAttribute("src", "../threeClass/img/" + imgs[index]);
// div添加圖片為子節點
tvDiv.appendChild(tvImg);
// 創建h1標簽節點
var tvh1=document.createElement("h1");
// 取得發布div框里填充的標題的值填充到h1標簽
var tvTitle=document.getElementById("title").value;
tvh1.innerText=tvTitle;
// 創建一個P標簽節點
var tvP=document.createElement("p");
// 創建兩個span標簽節點
var tvSpanOne=document.createElement("span");
var tvSpanTwo=document.createElement("span");
// 第一個span標簽取填充div里的下拉列表框所選的值
var tvSelect=document.getElementById("section").value;
tvSpanOne.innerText="板塊:" + tvSelect;
// 第二個span標簽取當前系統時間
var date=new Date();
var str=date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate() + "" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
tvSpanTwo.innerText="時間是:" + str;
// 兩個span標簽追加到p標簽節點里
tvP.appendChild(tvSpanOne);
tvP.appendChild(tvSpanTwo);
// 把div、h1、p 、標簽追加到li里
tvLi.appendChild(tvDiv);
tvLi.appendChild(tvh1);
tvLi.appendChild(tvP);
// 把添加好的li在插入到ul標簽節點里
var oldUL=document.getElementById("showContent");
// 把新添加的li節點插入到撈的li節點之前
oldUL.insertBefore(tvLi, oldUL.firstChild);
// 清除div里填充過的內容,如標題和內容部分
document.getElementById("title").value="";
document.getElementById("content").value="";
// 設置發布div隱藏
document.getElementById("showSubmit").style.display="none";
}
效果圖展示:file:///D:/ruanjian/VS/JS/threeClass/lunbotu.html
file:///D:/ruanjian/VS/JS/threeClass/lunbotu.html
一、構造函數法
function Dog() {
this.name='大黃';
this.call=function call() {
console.log('汪汪');
}
}
Dog.age=10;
Dog.prototype.eat=function () {
console.log('吃狗糧');
}
var dog1=new Dog();
dog1.call()
dog1.eat()
二、Object.create()
const dog={
name: '大黃',
call:function(){
console.log('汪汪');
}
}
const dog1=Object.create(dog);
dog1.call();
三、極簡主義法
var Dog={
create:function(){
var dog={};
dog.name='大黃';
dog.call=function(){
console.log('汪汪');
}
return dog;
}
}
var dog1=Dog.create();
dog1.call();
使用 class 關鍵字來聲明類。
class Person {
constructor(name,age){
this.name=name;
this.age=age
}
}
let user=new Person('張三',22);
console.log(user);
constructor 構造函數用于創建和初始化一個類
class Person {
// 私有變量
#_life='';
// 構造函數
constructor(name, age, sex, life) {
this.name=name;
this.age=age;
// 約定命名 通過在變量名稱前加一個下劃線來定義私有變量,實際上外部可以直接訪問
this._sex=sex;
// #作為前綴 定義私有作用域,外部無法直接訪問
this.#_life=life;
}
// Getter
get getName() {
return this.name
}
// Setter
set setName(name) {
this.name=name;
}
get sex() {
return this._sex;
}
get life() {
return `${this.#_life}年`
}
// 方法
sayHi() {
console.log(`hello,我是${this.name}`);
}
// 靜態方法 該方法不會被實例繼承,而是直接通過類來調用
static eat(food) {
console.log(`吃了${food}`);
}
// 私有方法
_a() {
console.log('約定命名的私有方法');
}
#_sleep() {
console.log(`${this.name}睡著了`);
}
sleep(){
this.#_sleep()
}
}
function a() {
console.log(`${this.name}睡著了`);
}
let user=new Person('張三', 22, '男', 99);
console.log(user);
console.log(user.getName);
user.name='王五'
console.log(user.name);
user.sayHi()
Person.eat('蘋果')
user._a()
// user.#__sleep() // 無法調用
user.sleep()
console.log(user.sex);
console.log(user.life);
*請認真填寫需求信息,我們會在24小時內與您取得聯系。