var person = { name: "Tom" };
function getName() { return this.name; }
// person.getName() // 報錯:person.getName is not a function
person 與 getName 是兩個**獨立變數**,無任何關聯。物件只能調用**自身屬性**(含繼承鏈)上的函數。
// 1. 字面量定義時掛載
var person = {
name: "Tom",
getName: function() { return this.name; }
};
// 2. 後續動態掛載
person.getName = function() { return this.name; };
// 3. 原型鏈掛載(所有實例共享)
function Person(name) { this.name = name; }
Person.prototype.getName = function() { return this.name; }
var p = new Person("Tom");
p.getName(); // "Tom"
obj.method()),this 指向該物件。getName()),非嚴格模式 this 指向 window,嚴格模式為 undefined。var getName = person.getName;
getName(); // this 丟失,輸出 undefined 或報錯
// 修正:用 bind 固定 this
var boundGetName = person.getName.bind(person);
boundGetName(); // "Tom"
理解「函數是獨立值,掛載到物件才成方法」是 JS 物件導向核心。