function initializeFriend(data) {
return {
fullName: `${data.firstName} ${data.lastName}`,
getThreeRandomPosts: function() {
// get three random posts from data.lastTenPosts
},
getDaysUntilBirthday: function() {
// use data.birthday to get the num days until birthday
}
};
}
const objectFriends = data.map(initializeFriend)
objectFriends[0].getThreeRandomPosts()
// Gets three of Bob Ross's posts
function initializeFriend(data) {
return {
fullName: `${data.firstName} ${data.lastName}`,
getThreeRandomPosts: function() {
// get three random posts from data.lastTenPosts
},
getDaysUntilBirthday: function() {
// use data.birthday to get the num days until birthday
},
greeting: function() {
return `Hello, this is ${fullName}'s data!`
}
};
}
注意:不要在全局作用域或在另一个函数作用域内的常规 ole 函数中使用 this!this 是一个面向对象的构造。因此,它只在对象(或类)的上下文中有意义!
让我们重构 initializeFriend,让它使用 this:
function initializeFriend(data) {
return {
lastTenPosts: data.lastTenPosts,
birthday: data.birthday,
fullName: `${data.firstName} ${data.lastName}`,
getThreeRandomPosts: function() {
// get three random posts from this.lastTenPosts
},
getDaysUntilBirthday: function() {
// use this.birthday to get the num days until birthday
},
greeting: function() {
const numDays = this.getDaysUntilBirthday()
return `Hello, this is ${this.fullName}'s data! It is ${numDays} until ${this.fullName}'s birthday!`
}
};
}
有时候,你希望 this 可以指向不一样的东西,比如事件处理程序就是一个很好的例子。假设我们想在用户点击链接时打开朋友的 Facebook 页面。我们可能会在对象中添加一个 onClick 方法:
function initializeFriend(data) {
return {
lastTenPosts: data.lastTenPosts,
birthday: data.birthday,
username: data.username,
fullName: `${data.firstName} ${data.lastName}`,
getThreeRandomPosts: function() {
// get three random posts from this.lastTenPosts
},
getDaysUntilBirthday: function() {
// use this.birthday to get the num days until birthday
},
greeting: function() {
const numDays = this.getDaysUntilBirthday()
return `Hello, this is ${this.fullName}'s data! It is ${numDays} until ${this.fullName}'s birthday!`
},
onFriendClick: function() {
window.open(`https://facebook.com/${this.username}`)
}
};
}