这里我试图给你一个例子来向你展示 JavaScript 中原型的优势。
例如:类
类、原型、面向对象 JavaScript 是构建复杂代码的范例。
在 JavaScript 中,我们使用 原型链,这是一种支持 OOP 模拟的底层特性,它本身就是一个引人注目的工具。
在新版本的 javascript 中,我们使用 new 和 class 关键字来自动创建对象和方法。
我们使用对象来表示具有数据和功能的真实对象。这样做主要有04种方式:
1。每个对象都存储自己的函数及其相关数据。
这是一个简单而简单的解决方案,但它的缺点是我们有两个具有相同功能的对象 => 每当我们创建一个新对象时,我们都会在内存中为所有数据和函数分配空间,而这些函数是相同的!不好的做法。这就是为什么出现第二种方法的原因:原型链;为什么我们使用原型”。
2。使用原型链:
检查下面的代码:
function userCreator (name, score) {
const newUser = Object.create(userFunctionStore); // to link to the the new created object to its functionalities
newUser.name = name;
newUser.score = score;
return newUser;
};
const userFunctionStore = {
increment: function(){this.score++;},
login: function(){console.log("Logged in");}
...
};
const user1 = userCreator("user1", 3);
const user2 = userCreator("user2", 5);
user1.increment();
我们将通用函数increment 存储在一个对象中。因此,当新创建的用户在其自己的对象中找不到函数时,它将通过其生成的链接从Object.create() 到functionStore 进行查找,在这里它可以获取它寻找的函数increment。
注意:所有对象都有一个__proto__ 属性,默认情况下链接到一个具有有用功能的大对象Object.prototype;像 e hasOwnProperty 检查对象是否具有给定属性的方法;我们可以通过userFunctionStore的__proto__属性在这里访问它。
结论
很好的方法,但很长而且不标准。
3。使用new 关键字自动完成繁重的工作。
看下面的代码
function userCreator(name, score) {
const newUser = Object.create(functionStore);
newUser this.name = name;
newUser this.score = score;
return newUser;
};
functionStore userCreator.prototype // {};
functionStore userCreator.prototype.increment = function(){
this.score++;
}
const user1 = userCreator("user1", 3);
使用new关键字会恢复到
function userCreator(name, score) {
this.name = name;
this.score = score;
};
userCreator.prototype // {};
userCreator.prototype.increment = function(){
this.score++;
}
const user1 = new userCreator("user1", 3);
所以new 会自动做 03 件主要事情:
-
this: {} => 自动创建 this 空对象以为其分配属性和值。
-
__proto: userCreator.prototype => 将__proto__ 隐藏属性添加到this 新创建的对象,并将其链接到userCreator.prototype,这是一个存储常用功能的对象。
-
return this => 返回 this 新创建的对象。
看看这段代码:
function userCreator(name, score){
this.name = name;
this.score = score;
}
userCreator.prototype.increment = function(){ this.score++; };
userCreator.prototype.login = function(){ console.log("login"); };
const user1 = new userCreator("user1", 3)
user1.increment()
这是上面解释的模拟。
user1 = {
name: 'user1',
score: 3,
__proto__: userCreator.prototype
}
userCreator = function + prototype =>
prototype = {
increment: function(){ this.score++; },
login: function(){ console.log("login"); }
}
结论
写得更快。在专业代码的实践中经常使用。许多开发人员不知道它是如何工作的。我们必须将函数的首字母大写,所以我们知道它需要new 才能工作!
4。 “语法糖”类
在对象创建器本身中编写我们的共享(通用)方法。代码应该是:
class UserCreator {
constructor (name, score){
this.name = name;
this.score = score;
}
increment (){ this.score++; }
login (){ console.log("login"); }
}
const user1 = new UserCreator("user1", 3);
user1.increment();
结论
这种方法正在成为一种新标准,感觉更像是其他语言(例如 Python)的风格
这个class 关键字非常重要,它只是用来消除使用newkeywords 的混淆,但在幕后它绝对与new 关键字一样工作。所以不要被其他语言弄糊涂了。
参考
所有学分都用于本课程JavaScript: The Hard Parts, v2。