我希望能够创建一个JS对象,该对象具有将对象中的现有字段组合在一起的字段,但我认为我有一个上下文问题"这个"我不确定如何解决。
这是我正在尝试做的:
function Person(firstName, lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
this.FullName = function ()
{
return this.FirstName + " " + this.LastName;
}
}
我希望使用FullName是一个jquery模板,但没有运气。
<script type="text/x-jquery-tmpl" id="tmplImg">
{{each people}}
<li>
${FullName}
</li>
{{/each}}
</script>
我认为它可以以某种方式完成,因为 Knockout.js 库能够以某种方式完成它,如本教程(步骤 4(所示。
http://learn.knockoutjs.com/#/?tutorial=templates
工作演示:
function Person(firstName, lastName) {
this.FirstName = firstName;
this.LastName = lastName;
var self = this;
this.FullName = function() {
return self.FirstName + ' ' + self.LastName;
}
}
我绝不是jQuery模板的专家,但这在我的测试中有效:
<script id="myTemplate" type="text/x-jquery-tmpl">
${$data.getFullName()}
</script>
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.getFullName = function() {
return this.firstName + " " + this.lastName;
};
var person = new Person("John", "Doe");
$("#myTemplate").tmpl(person).appendTo("#myOutput");
IAbstractDownvoteFactory的答案是一个可靠的答案,绝对值得一票赞成,但我只想在他/她的答案之外引入一层抽象:
请考虑以下帮助程序:
function createBoundMethodsFor(obj) {
var proto = obj.constructor.prototype
for(var method in proto)
if(typeof(proto[method]) === 'function')
obj[method] = function() { return proto[method].apply(obj, arguments); }
}
然后让我们再次看一下 person 的构造函数:
function Person(firstName, lastName) {
this.FirstName = firstName;
this.LastName = lastName;
createBoundMethodsFor(this)
}
Person.prototype.FullName = function() {
return this.FirstName + ' ' + this.LastName;
}
此帮助程序循环遍历对象prototype
中的所有functions
,并为每个构建绑定闭包,并将它们作为实例方法重写,但它们只是代理到原型方法。使用这样的帮助程序可能会使您的生活变得轻松得多,因为对象上的方法数量变得不平凡。
但请注意,像这样的绑定方法会导致您可能意想不到的有趣结果,例如:
var john = new Person("John", "Doe")
var jane = new Person("Jane", "Doe")
var bound = john.FullName
bound() // John Doe
bound.call(jane) // John Doe (Not Jane like you might expect)
var unbound = john.constructor.prototype.FullName;
unbound() // null
unbound.call(john) // John Doe
unbound.call(jane) // Jane Doe
在这里摆弄
使用您的脚本,我已经能够调用 FullName 并检索全名:
var pers = new Person("first", "last");
alert(pers.FullName());
这是你想要实现的吗?