【发布时间】:2019-04-16 08:35:30
【问题描述】:
我想知道这些符号有什么区别:
function Forms (formSelector) {
this.id;
this.formSelector = formSelector;
}
Forms.prototype.getAll = function () { return $(this.formSelector) } // get all forms in a JQuery object
Forms.prototype.get = function () { return $(this.getAll()).get(this.id) }
和
function Forms (formSelector) {
this.id;
this.formSelector = formSelector;
this.getAll = function () { return $(this.formSelector) }
this.get = function () { return $(this.getAll()).get(this.id) }
}
甚至
function Forms (formSelector) {
this.id;
this.formSelector = formSelector;
this.getAll = $(this.formSelector);
this.get = $(this.getAll()).get(this.id);
}
我什至可以这样写:
var Forms = {
constructor: function (formSelector) {
this.formSelector = formSelector;
return this.formSelector;
},
setId: function (id) { if (!isNaN(id) this.id = id; }
getAll: function () {
return $(Forms.constructor.formSelector); // this should work I think ?
}
}
这让我很困惑,我不太清楚在速度和清晰度以及封装它们的方法和属性方面,编写对象的最佳和更优化的方法是什么。
无论如何,我似乎可以通过以下方式修改我的属性:
var test = new Forms('.forms');
test.id = 10;
test.getAll = 'something';
// What I want is something like :
test.setId(10) // and test.id = X shouldn't work
谢谢!
【问题讨论】:
-
@Phiter 我不认为它是骗子
-
@Rajesh 接受的答案回应了这个确切的事情。至少前两个例子。
-
至少前两个例子意味着有些东西它没有回答
-
第三个例子不同,因为你返回的是一个对象,而不是一个函数。所以这个对象可以改变为如果它是在函数本身中创建的,你不能直接修改函数的对象。
-
@Rajesh 应该将多个问题标记为重复
标签: javascript jquery oop