gpt4 book ai didi

javascript - 浅复制问题

转载 作者:行者123 更新时间:2023-11-28 20:50:33 25 4
gpt4 key购买 nike

我只是尝试了一些简单的 JavaScript

name = 'velu' 
fname = name
name = 'valu'
console.log(fname) // would still print as velu...

如何处理生成的对象原型(prototype)发生更改并且生成的对象仍然具有旧对象的副本的情况..

情况是这样的...

function Cat(name){  
this.name = name
}
var garfield = new Cat('Garfield')
Cat.prototype.greet = function(){
console.log('Meow, I am ' + this.name)
}
function Animal(){}
Cat.prototype = new Animal
Cat.prototype.constructor = Cat
Animal.prototype.breed = function(){
console.log('Making a new animal!')
return new this.constructor()
}
var kitty = garfield.breed() // this will not work as it garfield still is pointing to the old prototype object of Cat ...

谢谢

最佳答案

您必须创建一个对象,该对象通过引用传递:

var name = { Value: 'velu' };
var fname = name;
name.Value = 'valu';
console.log(fname.Value);

关于javascript - 浅复制问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12536228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com