JavaScript的this关键字的理解(3)

<!DOCTYPE html><html lang="en"><body><script> var Person = function(x){ if(x){this.fullName = x}; }; Person.prototype.whatIsMyFullName = function() { return this.fullName; // 'this' refers to the instance created from Person() } var cody = new Person('cody lindley'); var lisa = new Person('lisa lindley'); // call the inherited whatIsMyFullName method, which uses this to refer to the instance console.log(cody.whatIsMyFullName(), lisa.whatIsMyFullName()); /* The prototype chain is still in effect, so if the instance does not have a fullName property, it will look for it in the prototype chain. Below, we add a fullName property to both the Person prototype and the Object prototype. See notes. */ Object.prototype.fullName = 'John Doe'; var john = new Person(); // no argument is passed so fullName is not added to instance console.log(john.whatIsMyFullName()); // logs 'John Doe' </script></body></html>

在prototype对象内的方法里使用this,this就指向实例。如果实例不包含属性的话,prototype查找便开始了。

提示

- 如果this指向的对象不包含想要查找的属性,那么这时对于任何属性都适用的法则在这里也适用,也就是,属性会沿着prototype链(prototype chain)上“寻找”。所以在我们的例子中,如果实例中不包含fullName属性,那么fullName就会查找Person.prototype.fullName,然后是Object.prototype.fullName。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzsfdf.html