每创建一个函数和或则对象都会创建一个原型对象prototype,在 prototype对象中又会像函数中创建this一样创建一个constructor 他用于指向拥有整个原型对象的函数或对象,通过new 该函数,对象会 继承该函数指针,此时会被定义为_proto_,通过它到公共容器(原型对象) 中匹配相应的属性和方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
<!--js 面向对象封装-->
let Book = function () {//定义一个方法 or 创建一个类
this.name = 'javascript';
}
Book.prototype.display = function(){//往公共空间(prototype)添加属性和方法
console.log(this.name);
return this.name;
}
console.log(new Book().display());//打印输出
</script>
</body>
</html>
私有。共有
<script>
<!--私有
javascript 通过函数作用域的特征来实现函数的私有化和公有化
公有-->
let Book = function (id,name,price) {
var num =1;//私有属性
this.name = name;//public
this.price = price;
this.id = id;
function checkId(){
// 私有方法
}
this.getname = function () {//特权方法(public)可倍访问的
return this.name;
}
this.setname = function (name) {//public
this.name = name;
}
this.setname(name);//构造函数
}
Book.isChinese = true;//私有部分
Book.prototype.isTime = "now time";//共有部分
let book = new Book(001,"javascript",100);
book.setname("java");
book.getname();
console.log(book.getname());
console.log(book.isChinese);
console.log(book.isTime);
</script>
闭包实现静态属性
<script>
<!--利用闭包实现静态变量-->
let Book = (function () {
let booknum = 100;//静态私有变量
function checkBook() {
// 静态私有方法
}
// 返回构造函数
return function (id,name,price) {
var name = name;//私有变量
this.id = id;//特权变量
this.price = price;
this.getId = function () {
return this.id;
}
this.setId = function (id) {
// console.log(id);
this.id = id;
}
}
})();
let book = new Book(12,"javascript",100);
book.setId(100);
console.log(book.getId());
</script>
安全模式
<script>
//new 关键字的作用可以看作当前对象的this 不断复制,如果没有
//new 关键字,这个函数就会立即执行,而函数在全局环境下执行
//this 就指向window 对象
// let Book = function () {
// this.name = "hello";
// }
// let a = Book();
// console.log(a.name);
// console.log(name);
let Book = function (id,name,price) {
if(this instanceof Book){
this.name = name;
}else {
return new Book(id,name,price);
}
}
let book = Book(0,"javascrit",100);
let book = new Book(0,"javascrit",100);
console.log(book.name);
</script>