当对象与原型有相同的属性,调用时的上下文指向问题
?
在查閱對象自定義事件及其觸發實現的過程中,發現了如下代碼:
即:構造函數的原型可以是其他構造方法new出來的對象實例,雖然理解構造函數原型就是一個對象,但通常都是用對象直接量來指定,如:F.prototype ={},這種用法,引起了一些思考:如果原型對象和構造函數定義了完全相同的屬性,那么原型方法調研時,作用域是原型對象還是新的對象?為此,做了一下驗證:
function ancestor(){this.name ='default';this.age = 18;}ancestor.prototype = {printInfo:function(){console.log( this.name + "," + this.age );}};function parent( _name,_age ){this.name = _name;this.age = _age;}parent.prototype = new ancestor();var o1 = new parent('tester',20);var o2 = new parent();console.log( o1 );console.log( o2 );打印結果如下:
可見,對象原型和對象自身,都保留了各自的'name'和'age'屬性,繼續調用對象o1,o2繼承自原型的printInfo方法,代碼如下:
function ancestor(){this.name ='default';this.age = 18;}ancestor.prototype = {printInfo:function(){console.log( this.name + "," + this.age );}};function parent( _name,_age ){this.name = _name;this.age = _age;}parent.prototype = new ancestor();var o1 = new parent('tester',20);var o2 = new parent();console.log('o1-----:');console.log( o1 );console.log('o2-----:');console.log( o2 );o1.printInfo();o2.printInfo();執行結果:
可見:o1,o2在調用繼承自原型的方法時,如果自身有了對應的屬性定義,則調研的就是對象自身屬性,不會上溯至原型對象。
如想切換作用域至原型對象,可以利用方法的call方式來實現:
o1.printInfo.call(Object.getPrototypeOf(o1)); o2.printInfo.call(Object.getPrototypeOf(o2));結果:
?
?
?-------------------------補充---------------------------------------------------------------------------------------------------
?
上面的情況下,當對象沒有定義與原型重合的屬性時,調用原型方法,會是什么情況?代碼如下:
function ancestor(){this.name ='default';this.age = 18;}ancestor.prototype = {printInfo:function(){console.log( this.name + "," + this.age );}};function parent(){}parent.prototype = new ancestor();var o1 = new parent();o1.printInfo();運行結果:
可見,此時最終函數執行的作用域是其原型對象,其實這就是“作用域鏈”的概念:當對象的方法用到某屬性時,會按照對象→原型parent1→原型parent2的鏈式方式,不斷向上追溯查找該屬性,直至找到或者為undefined.
?
轉載于:https://www.cnblogs.com/surfer/p/9681514.html
總結
以上是生活随笔為你收集整理的当对象与原型有相同的属性,调用时的上下文指向问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Django--分页器(paginato
- 下一篇: Django form表单