了解Javascript中的变量更新

时间:2018-02-16 04:07:19

标签: javascript

我有点困惑,可能是一个简单的话题。我今天第一次遇到这个并且有点吃惊。假设您有以下代码

roundPx

现在有趣的部分是你更新public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(rect); final float roundPx = 12; paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; }

let x = {a: 100}
let y = {b: x} //Note the x value

它会在两个对象中更新。我的印象是x尽管使用了对x.a = 200 console.log(x) console.log(y) > { a: 200 } > { b: { a: 200 } } 的引用,但仍会创建一个全新的对象。现在,我的想法被这个事实所震撼。这里发生了什么?这里的主题是什么?

1 个答案:

答案 0 :(得分:0)

在你的情况下,只是制作同一个对象的浅表副本。要创建新对象(深层副本),请使用Object.assign



let x = {
  a: 100
}
let y = {
  b: Object.assign({}, x)
}

x.a = 200;

console.log(x)
console.log(y)