js 面向对象例子
var Book = function (id, name, price) {//private(在函數(shù)內(nèi)部定義,函數(shù)外部訪問不到,實(shí)例化之后實(shí)例化的對象訪問不到) var num = 1; var id = id; function checkId() { console.log('private') } //protected(可以訪問到函數(shù)內(nèi)部的私有屬性和私有方法,在實(shí)例化之后就可以對實(shí)例化的類進(jìn)行初始化拿到函數(shù)的私有屬性) this.getName = function () { console.log(id) } this.getPrice = function () { console.log(price) } //public(實(shí)例化的之后,實(shí)例化的對象就可以訪問到了~) this.name = name; this.copy = function () { console.log('this is public') } } //在Book的原型上添加的方法實(shí)例化之后可以被實(shí)例化對象繼承 Book.prototype.proFunction = function () { console.log('this is proFunction') } //在函數(shù)外部通過.語法創(chuàng)建的屬性和方法,只能通過該類訪問,實(shí)例化對象訪問不到 Book.setTime = function () { console.log('this is new time') } var book1 = new Book('111','悲慘世界','$99') book1.getName(); // 111 getName是protected,可以訪問到類的私有屬性,所以實(shí)例化之后也可以訪問到函數(shù)的私有屬性 book1.checkId(); //報(bào)錯(cuò)book1.checkId is not a function console.log(book1.id) // undefined id是在函數(shù)內(nèi)部通過定義的,是私有屬性,所以實(shí)例化對象訪問不到 console.log(book1.name) //name 是通過this創(chuàng)建的,所以在實(shí)例化的時(shí)候會(huì)在book1中復(fù)制一遍name屬性,所以可以訪問到 book1.copy() //this is public book1.proFunction(); //this is proFunction Book.setTime(); //this is new time book1.setTime(); //報(bào)錯(cuò)book1.setTime is not a function
轉(zhuǎn)載于:https://www.cnblogs.com/zuichumx0826/p/9355399.html
總結(jié)
- 上一篇: 关于线性条形码符号的解读(一)
- 下一篇: Python全栈工程师(文件操作、编码)