Last active
August 31, 2018 13:38
-
-
Save KScaesar/f07f3ce9c0a3e1e4ac05e66f2674dc80 to your computer and use it in GitHub Desktop.
test prototype
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function Foo(){ | |
| this.testArr=[2,4]; | |
| }; | |
| Foo.prototype={ | |
| str:'test', | |
| num:1, | |
| arr:[1,2], | |
| obj:{a:2} | |
| }; | |
| foo1=new Foo(); | |
| foo2=new Foo(); | |
| foo2; // Foo {testArr: Array(2)} | |
| // 只得到建構函式中的特性testArr | |
| //foo2修改字串,foo1沒影響 | |
| foo1.str; // "test" | |
| foo2.str+="測試"; | |
| foo1.str; // "test" | |
| //foo2修改數值,foo1沒影響 | |
| foo1.num; // 1 | |
| foo2.num+=2; | |
| foo1.num; // 1 | |
| //foo2修改陣列,foo1被影響 | |
| foo1.arr; // [1, 2] | |
| foo2.arr.push(4); | |
| foo1.arr; // [1, 2, 4] | |
| //foo2修改物件,foo1被影響 | |
| foo1.obj; // {a: 2} | |
| foo2.obj.a=444; | |
| foo1.obj; // {a: 444} | |
| foo2; // Foo {testArr: Array(2), str: "test測試", num: 3} | |
| // 參考型別的特性,不會追蹤原型鏈,新增特性到自己的物件 | |
| //從新給予foo2.obj新的物件,則可以特性到自己的物件,call by sharing的原理 | |
| foo2.obj={ | |
| a: 444 | |
| } | |
| foo2; // Foo {testArr: Array(2), str: "test測試", num: 3, obj: {…}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment