Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 50 additions & 49 deletions src/v2/cookbook/adding-instance-properties.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
---
title: Adding Instance Properties
title: Menambah Properti Instance
type: cookbook
order: 2
---

## Base Example
## Contoh Dasar

Mungkin ada data/utilitas yang ingin anda gunakan di banyak komponen, tetapi anda tidak ingin [mencemari scope global](https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch3.md). Dalam kasus ini, anda dapat membuatnya tersedia untuk setiap *instance* Vue dengan mendefinisikannya pada *prototype*:

There may be data/utilities you'd like to use in many components, but you don't want to [pollute the global scope](https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch3.md). In these cases, you can make them available to each Vue instance by defining them on the prototype:

```js
Vue.prototype.$appName = 'My App'
Vue.prototype.$appName = 'Aplikasi saya'
```

Now `$appName` is available on all Vue instances, even before creation. If we run:
Sekarang `$appName` tersedia di semua *instance* Vue, bahkan sebelum pembuatan. Jika kita jalankan:

```js
new Vue({
Expand All @@ -22,32 +23,32 @@ new Vue({
})
```

Then `"My App"` will be logged to the console!
Kemudian `"Aplikasi saya"` akan tercatat pada konsol!

## The Importance of Scoping Instance Properties
## *Scoping* Properti *Instance*

You may be wondering:
Anda mungkin bertanya:

> "Why does `appName` start with `$`? Is that important? What does it do?
> "Mengapa `appName` dimulai dengan `$`? Apakah itu penting? Apa fungsinya?

No magic is happening here. `$` is a convention Vue uses for properties that are available to all instances. This avoids conflicts with any defined data, computed properties, or methods.
Tidak ada keajaiban yang terjadi disini. `$` adalah konvensi yang digunakan Vue untuk properti yang tersedia untuk semua *instance*. Ini menghindari konflik dengan data yang didefinisikan, properti yang dihitung, atau metode.

> "Conflicts? What do you mean?"
> "Konflik? Apa yang anda maksud?"

Another great question! If you set:
Pertanyaan bagus lainnya! Jika Anda menetapkan:

```js
Vue.prototype.appName = 'My App'
Vue.prototype.appName = 'Aplikasi saya'
```

Then what would you expect to be logged below?
Lalu apa yang anda harapkan untuk tercatat di bawah ini?

```js
new Vue({
data: {
// Uh oh - appName is *also* the name of the
// instance property we defined!
appName: 'The name of some other app'
// Uh oh - appName adalah nama properti
// *instance* juga yang kita definisikan!
appName: 'Nama aplikasi lain'
},
beforeCreate: function() {
console.log(this.appName)
Expand All @@ -58,13 +59,13 @@ new Vue({
})
```

It would be `"My App"`, then `"The name of some other app"`, because `this.appName` is overwritten ([sort of](https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch5.md)) by `data` when the instance is created. We scope instance properties with `$` to avoid this. You can even use your own convention if you'd like, such as `$_appName` or `ΩappName`, to prevent even conflicts with plugins or future features.
Ini akan menjadi `"Aplikasi saya"`, lalu `"Nama aplikasi lain"`, karena `this.appName` ditimpa ([semacam](https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch5.md)) oleh `data` saat instance dibuat. Kami memberi *scope* properti *instance* dengan `$` untuk menghindari hal ini. Anda bahkan dapat menggunakan konvensi anda sendiri jika ingin, seperti `$ _appName` atau` ΩappName`, untuk mencegah konflik bahkan dengan *plugin* atau fitur-fitur masa depan.

## Real-World Example: Replacing Vue Resource with Axios
## Contoh Dunia Nyata: Mengganti Sumber Vue dengan Axios

Let's say you're replacing the [now-retired Vue Resource](https://medium.com/the-vue-point/retiring-vue-resource-871a82880af4). You really enjoyed accessing request methods through `this.$http` and you want to do the same thing with Axios instead.
Katakanlah anda mengganti [Sumber Vue yang sekarang sudah pensiun](https://medium.com/the-vue-point/retiring-vue-resource-871a82880af4). Anda benar-benar menikmati mengakses metode *request* melalui `this.$http` dan anda ingin melakukan hal yang sama dengan Axios sebagai gantinya.

All you have to do is include axios in your project:
Yang harus anda perlu lakukan adalah memasukkan axios dalam proyek Anda:

```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.15.2/axios.js"></script>
Expand All @@ -76,13 +77,13 @@ All you have to do is include axios in your project:
</div>
```

Alias `axios` to `Vue.prototype.$http`:
Memberi alias `axios` ke `Vue.prototype.$http`:

```js
Vue.prototype.$http = axios
```

Then you'll be able to use methods like `this.$http.get` in any Vue instance:
Maka anda akan dapat menggunakan metode seperti ini `this.$http.get` dalam setiap *instance* Vue:

```js
new Vue({
Expand All @@ -101,11 +102,11 @@ new Vue({
})
```

## The Context of Prototype Methods
## Konteks Metode Prototype

In case you're not aware, methods added to a prototype in JavaScript gain the context of the instance. That means they can use `this` to access data, computed properties, methods, or anything else defined on the instance.
Jika anda tidak menyadari, metode yang ditambahkan ke *prototype* dalam JavaScript memperoleh konteks *instance*. Itu berarti mereka dapat menggunakan `this` untuk mengakses data, properti yang dihitung (computed properties), metode, atau apa pun yang didefinisikan pada *instance*.

Let's take advantage of this in a `$reverseText` method:
Mari kita manfaatkan ini dalam sebuah metode `$reverseText`:

```js
Vue.prototype.$reverseText = function(propertyName) {
Expand All @@ -117,17 +118,17 @@ Vue.prototype.$reverseText = function(propertyName) {

new Vue({
data: {
message: 'Hello'
message: 'Halo'
},
created: function() {
console.log(this.message) // => "Hello"
console.log(this.message) // => "Halo"
this.$reverseText('message')
console.log(this.message) // => "olleH"
console.log(this.message) // => "olaH"
}
})
```

Note that the context binding will **not** work if you use an ES6/2015 arrow function, as they implicitly bind to their parent scope. That means the arrow function version:
Perhatikan bahwa pengikatan (binding) konteks **tidak** berfungsi jika anda menggunakan fungsi panah (arrow function) ES6/2015, karena mereka secara implisit mengikat (bind) ke *scope* induk. Itu berarti versi fungsi panah berikut:

```js
Vue.prototype.$reverseText = propertyName => {
Expand All @@ -138,37 +139,37 @@ Vue.prototype.$reverseText = propertyName => {
}
```

Would throw an error:
Akan melempar galat:

```log
Uncaught TypeError: Cannot read property 'split' of undefined
```

## When To Avoid This Pattern
## Kapan Harus Menghindari Pola Ini

As long as you're vigilant in scoping prototype properties, using this pattern is quite safe - as in, unlikely to produce bugs.
Selama anda waspada dalam *scoping* pada properti *prototype*, menggunakan pola ini cukup aman - seperti pada, tidak mungkin mengasilkan *bugs*.

However, it can sometimes cause confusion with other developers. They might see `this.$http`, for example, and think, "Oh, I didn't know about this Vue feature!" Then they move to a different project and are confused when `this.$http` is undefined. Or, maybe they want to Google how to do something, but can't find results because they don't realize they're actually using Axios under an alias.
Namun, terkadang dapat menyebabkan kebingungan dengan pengembang lain. Mereka mungkin melihat `this.$http`, sebagai contoh, dan berpikir, "Oh, saya tidak tahu tentang fitur Vue ini!" Kemudian mereka pindah ke proyek lain dan bingung ketika `this.$http` tidak terdefisini (undefined). Atau, mungkin mereka ingin mencari di Google cara melakukan sesuatu, tetapi tidak dapat menemukan hasil karena mereka tidak menyadari bahwa mereka benar-benar menggunakan Axios dengan alias.

**The convenience comes at the cost of explicitness.** When looking at a component, it's impossible to tell where `$http` came from. Vue itself? A plugin? A coworker?
**Kemudahan datang dengan harga kesederhanaan.** Ketika melihat pada sebuah komponen, tidak mungkin untuk mengetahui dari mana `$http` berasal. Vue sendiri? *Plugin*? Rekan kerja?

So what are the alternatives?
Jadi apa saja alternatifnya?

## Alternative Patterns
## Pola Alternatif

### When Not Using a Module System
### Ketika Tidak Menggunakan Sebuah Sistem Modul

In applications with **no** module system (e.g. via Webpack or Browserify), there's a pattern that's often used with _any_ JavaScript-enhanced frontend: a global `App` object.
Dalam aplikasi **tanpa** sistem modul (mis. Via Webpack atau Browserify), ada pola yang sering digunakan dengan Frontend yang disempurnakan dengan JavaScript (JavaScript-enhanced frontend) apapun: objek `App` global.

If what you want to add has nothing to do with Vue specifically, this may be a good alternative to reach for. Here's an example:
Jika yang ingin anda tambahkan tidak ada hubungannya dengan Vue secara khusus, ini mungkin merupakan alternatif yang baik untuk dicapai. Berikut sebuah contoh:

```js
var App = Object.freeze({
name: 'My App',
name: 'Aplikasi saya',
version: '2.1.4',
helpers: {
// This is a purely functional version of
// the $reverseText method we saw earlier
// Ini adalah versi fungsional murni dari
// metode $reverseText yang kita lihat sebelumnya
reverseText: function(text) {
return text
.split('')
Expand All @@ -179,11 +180,11 @@ var App = Object.freeze({
})
```

<p class="tip">If you raised an eyebrow at `Object.freeze`, what it does is prevent the object from being changed in the future. This essentially makes all its properties constants, protecting you from future state bugs.</p>
<p class="tip">Jika Anda mengangkat alis pada `Object.freeze`, yang dilakukannya adalah mencegah objek diubah di masa mendatang. Ini pada dasarnya membuat semua properti miliknya konstan, melindungi anda dari kondisi *bug* di masa depan.</p>

Now the source of these shared properties is more obvious: there's an `App` object defined somewhere in the app. To find it, developers can run a project-wide search.
Sekarang sumber dari properti yang dibagikan ini lebih jelas: ada objek `App` yang didefinisikan di suatu tempat dalam aplikasi. Untuk menemukannya, pengembang dapat melakukan pencarian di seluruh proyek.

Another advantage is that `App` can now be used _anywhere_ in your code, whether it's Vue-related or not. That includes attaching values directly to instance options, rather than having to enter a function to access properties on `this`:
Keuntungan lain adalah bahwa `App` sekarang dapat digunakan _di manapun_ dalam kode Anda, apakah itu terkait Vue atau tidak. Itu termasuk melampirkan nilai secara langsung ke opsi *instance*, daripada harus memasukkan fungsi untuk mengakses properti di `this`:

```js
new Vue({
Expand All @@ -196,8 +197,8 @@ new Vue({
})
```

### When Using a Module System
### Ketika Menggunakan Sebuah Sistem Modul

When you have access to a module system, you can easily organize shared code into modules, then `require`/`import` those modules wherever they're needed. This is the epitome of explicitness, because in each file you gain a list of dependencies. You know _exactly_ where each one came from.
Ketika Anda memiliki akses ke sistem modul, anda dapat dengan mudah mengatur kode bersama ke dalam modul, kemudian `require`/`import` modul-modul tersebut di manapun dibutuhkan. Ini adalah lambang kesederhanaan, karena dalam setiap berkas anda mendapatkan daftar dependensi (dependencies). Anda tahu _persis_ tepatnya di mana masing-masing berkas tersebut berasal.

While certainly more verbose, this approach is definitely the most maintainable, especially when working with other developers and/or building a large app.
Meskipun tentu saja lebih bertele-tele, pendekatan ini jelas yang paling bisa dipelihara, terutama ketika bekerja dengan pengembang lain dan/atau membangun sebuah aplikasi besar.