比较2种不同的Javascript构造函数方法
我是JavaScript新手,发现下面两种不同的方法能够实例化对象 我查看了从两个构造函数创建的对象,它对我来说似乎是相同的 但我不确定这两种方法的区别是什么?在哪种情况下,一种方法比另一种更好 谁能解释一下吗?多谢各位 Person1.js比较2种不同的Javascript构造函数方法,javascript,constructor,Javascript,Constructor,我是JavaScript新手,发现下面两种不同的方法能够实例化对象 我查看了从两个构造函数创建的对象,它对我来说似乎是相同的 但我不确定这两种方法的区别是什么?在哪种情况下,一种方法比另一种更好 谁能解释一下吗?多谢各位 Person1.js function Person1(name){ this.name = name; this.initialize(); } Person1.prototype.initialize = function (todoName) {
function Person1(name){
this.name = name;
this.initialize();
}
Person1.prototype.initialize = function (todoName) {
console.log("Initalize function Person 1 class"+this);
f1(this);
}
function f1(caller) {
console.log("F1 Person 1 class"+this);
console.log(this);
console.log("F1 Person 1 class caller"+caller);
console.log(caller);
}
Person2.js
var Person2 = (function(){
function Person2(name){
this.name = name;
this.initialize();
}
Person2.prototype.initialize = function (todoName) {
console.log("Initalize function Person 2 class"+this);
f1(this);
}
function f1(caller) {
console.log("F1 Person 2 class"+this);
console.log(this);
console.log("F1 Person 2 class caller"+caller);
console.log(caller);
}
return Person2;
})();
使用以下代码实例化对象:
var p1 = new Person1("P1");
var p2 = new Person2("P2");
console.log("Completed ");
console.log("P1 ");
console.log(p1);
console.log("P2 ");
console.log(p2);
Person2被包装在所谓的立即调用函数表达式或IIFE中。您会注意到,在最后,它返回Person2,这就是示例第一行的赋值有效的原因
<> P>您认为使用这种方法的原因是,在iFILE中打包代码使您具有全局范围干净的含义,例如在浏览器中,窗口对象不会被一堆全局属性所困扰。
作为初学者,我可能会选择Person1方法,因为它在视觉上更简单,更容易跟踪正在发生的事情。然而,随着您的进步,请记住上述内容,并考虑什么对代码库的可维护性最有利