我希望能够创建一个JS对象,该对象具有将对象中的现有字段组合在一起的字段,但我认为我对“this”存在上下文问题,我不确定如何解决。
这是我正在尝试做的事情:
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)。
答案 0 :(得分:2)
function Person(firstName, lastName) {
this.FirstName = firstName;
this.LastName = lastName;
var self = this;
this.FullName = function() {
return self.FirstName + ' ' + self.LastName;
}
}
答案 1 :(得分:0)
使用您的脚本,我已经能够调用FullName并检索全名:
var pers = new Person("first", "last");
alert(pers.FullName());
这是你想要完成的吗?
答案 2 :(得分:0)
我绝不是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");
答案 3 :(得分:0)
IAbstractDownvoteFactory的答案是一个可靠的答案,绝对值得一个upvote,但我只是想在他/她的答案之外引入一层抽象:
考虑以下帮助者:
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); }
}
然后让我们再看一下人的构造函数:
function Person(firstName, lastName) {
this.FirstName = firstName;
this.LastName = lastName;
createBoundMethodsFor(this)
}
Person.prototype.FullName = function() {
return this.FirstName + ' ' + this.LastName;
}
这个助手循环遍历对象functions
中的所有prototype
,并为每个对象构建绑定闭包,并将它们作为实例方法覆盖,但它们只是代理到原型方法。使用这样的帮助器可能会使您的生活变得更加容易,因为对象上的方法数量变得非常重要。
但请注意,这样的绑定方法会产生您可能不期望的有趣结果,例如:
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