1

JS把某个对象复制给另外一个对象,报了Invalid left-hand side in assignment。

在代码的17行,我想把这个对象的左边一个对象复制给这个对象,但是始终搞不定

var MATRIX = 5;
var Point = function(x,y){
    this.x = x;
    this.y = y;
    this.nth = (this.y*MATRIX) + this.x;
    return this;
}
Point.prototype = {
    constructor : Point,
    left : function(){
        if(this.x > 0){
            return new Point(this.x-1,this.y);
        }
    },
    moveL : function(){
        //这一行总是报错 Invalid left-hand side in assignment
        this = this.left();
    }
}

var p = new Point(2,3);
p.left();
p.moveL();

我哪里出了问题呢?

2017-12-27 提问

查看全部 7 个回答

0

Object.assign(this, this.left())

推荐答案

2

已采纳
var MATRIX = 5;

function extendTo (base, receiver) {
    var receiver = receiver || {};
    for(var prop in base) {
        if ( base.hasOwnProperty(prop)) {
            receiver[prop] = base[prop];
        }
    }
    return receiver;
}

var Point = function(x,y){
    this.x = x;
    this.y = y;
    this.nth = (this.y*MATRIX) + this.x;
    return this;
}
Point.prototype = {
    constructor : Point,
    left : function(){
        if(this.x > 0){
            return new Point(this.x-1,this.y);
        }
    },
    moveL : function(){
        extendTo(this.left(), this)
    }
}

var p = new Point(2,3);
console.log(p.x, p.y, p.nth);   //2,3,17

p.moveL();
console.log(p.x, p.y, p.nth);   //1,3,16

你可以看下我的extendTo函数

推广链接