简体   繁体   中英

How to achieve JavaScript Object inheritance?

I want create a new JavaScript object based on an existing JavaScript object.
Till now my research led me to jQuery extend function.

example:

var object1 = {
    name:'same name',
    age:'1',
    occupation:'programmer'
}
var object2 = {
    name:'same new name'
}

Now, when I call:

$.extend({},object1,object2);

it works perfectly, my problem is when I have object member within the object!

var object1 = {
    name:'same name',
    age:19,
    occupation:'programmer',
    parent:{
        name:'parent name',
        age:35
    }
}
var object2 = {
    name:'same new name',
    parent:{
        age:40
    }
}

Now, when I call

$.extend({},object1,object2);

object1.parent is:

{
    age:40
}

I want it to be:

{
    name:'same new name',
    age:40
}

Is there a way to achieve this?

对jQuer.extend()方法使用deep参数,您的代码应为:

$.extend(true,{},object1,object2)

您要做的是进行深度扩展

$.extend(true, {},object1,object2);

You can force $.extend to do a deep copy like so:

$.extend(true, {},object1,object2);

although $.extend doesn't create an inheritance hierarchy so much as it just copies properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM