鍍金池/ 問答/HTML/ 為什么使用this.__proto__[key]=obj[key]會多出一段下面

為什么使用this.__proto__[key]=obj[key]會多出一段下面的輸出

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
</head>

<body>

<script type="text/javascript">

function a() {
    console.log("I'am a function.");
}
//b是實例化對象,a是構造函數(shù)
var b = new a();
//console.log(b.__proto__)

var $ = function() {
    extend = function(obj)
    {
        console.log(obj)
        console.log('擴展')
        for(var key in obj)
        {
            console.log('key');
            console.log(key);
            
            console.log('obj');
            console.log(obj);
         
            this.__proto__[key]=obj[key];
        }
    }  
    return { extend : extend };  
}();  

$.extend({
    myFunction:function(obj)
    {
        console.log('我函數(shù)')  
    }
})

console.log('第二次')

$.extend({
    showScreen:function(obj)
    {
        console.log('展示的大屏幕')  
    }
})


$.showScreen();

$.myFunction();

</script>


</body>
</html>

圖片描述

我每次只是增加一個key
第二次增加的key不包括第一次的key
但是第一次的key還是顯示出來了

回答
編輯回答
命多硬

因為你為this.__proto__添加了myFunctionshowScreen兩個key啊...在遍歷的時候就會輸出兩個吶...

那我改出來一個大致能滿足你的需求的版本,你可以瞧一眼...

<script>
        
function a() {
    console.log("I'am a function.");
}
//b是實例化對象,a是構造函數(shù)
var b = new a();
//console.log(b.__proto__)

var $ = function() {
    extend = function(obj)
    {
        console.log(obj)
        console.log('擴展')
        for(var key in obj)
        {
            console.log('key');
            console.log(key);
            
            console.log('obj');
            console.log(obj);
        
            // this.__proto__[key]=obj[key];
        }
    }  
    return { extend : extend };  
}();  

$.extend({
    myFunction:function(obj)
    {
        console.log('我函數(shù)')  
    }
})

console.log('第二次')

$.extend({
    showScreen:function(obj)
    {
        console.log('展示的大屏幕')  
    }
})


// $.showScreen;

// $.myFunction;

</script>
2017年3月14日 00:48
編輯回答
互擼娃

給你個例子

var a = {};
var b = {};
a.__proto__.show = function(){
    console.log("show")
}
b.show();//show
for(var key in b){
    console.log(key)//show
}

改良后

var $ = {
    a: "aaaa",
    extend: function (obj) {
        console.log('擴展:', obj)
        for (var key in obj) {
            console.log('key:', key);
            console.log('value:', obj[key]);

            this[key] = obj[key];
        }
    }
}

$.extend({
    myFunction: function () {
        console.log('我函數(shù)',"a:", this.a);
        return this;
    }
})
console.log('第二次')
$.extend({
    showScreen: function () {
        console.log('展示的大屏幕')
        this.myFunction();
        return this;
    }
})

$.showScreen().myFunction();
2018年1月20日 12:14