Clone an object with for.in and hasOwnproperty, but it is reported that the property of the cloned object cannot be null. Why? It's worth it.

    function Fn() {
        this.x=100;
        this.y=200;
        this.getY=function(){
            console.log(this.y);
            
        }
    }
    var f1=new Fn;
    var f3=null;
    cloneObj(f3,f1);
    console.log(f3);
    
    function cloneObj(obj1,obj2) {
        for (var key in obj2) {
            if (obj2.hasOwnProperty(key)) {
                console.log(obj2[key]);     //100
                obj1[key]=obj2[key];        //Cannot set property "x" of null
            }
        }
        return obj1;
    }

clipboard.png

I really don"t understand. When printing, it is clear that obj2 [x] = 100, why the next line is wrong?

Mar.10,2021

f3 is null, that is, obj1 is null
null ['x'] = obj2 ['x'] what the heck is


assign f3 to {}


first assign f3 = {},
then you can simply clone:

.
function Fn() {
    this.x=100;
    this.y=200;
    this.getY=function(){
        console.log(this.y);
        
    }
}
var f1=new Fn;
var f3={};
Object.assign(f3,f1)
Menu