mit*_*esh 0 javascript prototype class object
阅读可以使用哪些技术在JavaScript中定义一个类,以及它们的权衡取舍是什么?在stackoverflow上我明白我可以通过定义一个类
方法1:
function Person(name, gender){
this.name = name;
this.gender = gender;
}
Run Code Online (Sandbox Code Playgroud)
并在原型中添加函数,以避免每次实例化时重新创建成员函数.喜欢
Person.prototype.speak = function(){
alert("my name is" + this.name);
}
Run Code Online (Sandbox Code Playgroud)
并通过创建其实例
var person = new Person("Bob", "M");
Run Code Online (Sandbox Code Playgroud)
我认为使用新的关键字就可以创建相同的对象
方法2:
var Person = function (name, gender) {
return {name:name, gender:gender};
}
person = Person("Bob", "M");
Run Code Online (Sandbox Code Playgroud)
第二种方法是否完成了第一种方法完成相同的操作?如果是这样的话,我将如何在第二种方法中通过原型模拟添加函数(正如我们在方法1中所说的那样)?
不,方法2!=方法1.第二种方法是创建一个新的匿名对象,其原型指向Object.prototype第一个,而第一个是创建一个具有指向的原型的新对象Person.prototype.
在伪代码中:
// Method #1
function Person(name, gender) {
// The magic JS does *for us* (but *only* when invoked with `new`)
var this = {};
// __proto__ is the *internal* prototype reference
// It's not required to be accessible unless you're in an ES6 environment.
this.__proto__ = Person.prototype;
// Person.prototype is also created by JS for us
// and provided with a reference (among other things)
// to this function as prototype.constructor.
// Our stuff
this.name = name;
this.gender = gender;
// More JS magic
return this;
}
// Method #2
function Person(name, gender) {
// Just our stuff - no magic JS goodness here
return {
name: name, gender: gender
};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
146 次 |
| 最近记录: |