Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 父对象的命名空间继承方法_Javascript - Fatal编程技术网

Javascript 父对象的命名空间继承方法

Javascript 父对象的命名空间继承方法,javascript,Javascript,名称空间和对象有问题。我是新来的,所以真的很困惑。 我希望数组中的一个对象继承父对象方法 这是我的密码: var obj = { arr1:['one', 'two'], arr2:[], init:function() { for(var x=0; x<this.arr1.length; x++) { this.arr2.push(new this.myfunc1(x, this.arr1[x])); }

名称空间和对象有问题。我是新来的,所以真的很困惑。 我希望数组中的一个对象继承父对象方法

这是我的密码:

 var obj = {

   arr1:['one', 'two'],
   arr2:[],

   init:function() {
       for(var x=0; x<this.arr1.length; x++) {
           this.arr2.push(new this.myfunc1(x, this.arr1[x]));
       }
       this.arr2[0].myfunc2();
   },

   myfunc1:function(x, name) {
        this.index = x;
        this.name = name;
   },

   myfunc2:function() {
        alert(this.index + ' ' + this.name);
   }

};

obj.init();
var obj={
arr1:[1',2'],
arr2:[],
init:function(){

如我所见,对于(var x=0;x,您希望在正在创建的对象中使用“obj”方法

this.arr2.push(new this.myfunc1(x, this.arr1[x]));
很简单,这些对象的构造函数是.myfunct1(),因此必须在构造函数的prototype属性中指定prototype对象:

this.myfunct1.prototype = this;

for(var x=0; x<this.arr1.length; x++) {
    this.arr2.push(new this.myfunc1(x, this.arr1[x]));
}

// WORKS!!!
this.arr2[0].myfunc2();
this.myfunct1.prototype=this;

对于席瓦里x=0;XI可以理解你的困惑。你习惯于使用类。忘记你所知道的关于经典OOP的所有内容。JavaScript是面向对象的,但是使用原型来继承。但是在你的情况下,我认为你不需要继承。无论如何,我会发布一个可能的解决方案,同时我建议你赶上一些阅读。g关于JavaScript OOP;-)进一步检查后,我自己也感到困惑。你能澄清一下你想要完成什么吗?在我看来,你是在试图将一个数组复制到另一个数组?是
obj
你的名称空间还是你想要重用的对象?是的,太好了!非常感谢!:)救了我一天,祝你过得愉快!