Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.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 如何在非ES5中实现Object.create()_Javascript_Prototypal Inheritance - Fatal编程技术网

Javascript 如何在非ES5中实现Object.create()

Javascript 如何在非ES5中实现Object.create(),javascript,prototypal-inheritance,Javascript,Prototypal Inheritance,最近,我读了很多关于Javascript的书籍和文章,对于非ES5环境中Object.create的公认版本感到困惑。道格拉斯·克罗克福德(Douglas Crockford)和斯托扬·斯特凡诺夫(Stoyan Stefanov)都提到了在非ES5环境中重新创建Object.create功能的方法,尽管它们的函数名称不同,但您可以看到以下实现: function inherit(child, parent) { var f = function() {}; f.prototype

最近,我读了很多关于Javascript的书籍和文章,对于非ES5环境中Object.create的公认版本感到困惑。道格拉斯·克罗克福德(Douglas Crockford)和斯托扬·斯特凡诺夫(Stoyan Stefanov)都提到了在非ES5环境中重新创建Object.create功能的方法,尽管它们的函数名称不同,但您可以看到以下实现:

function inherit(child, parent) {
    var f = function() {};
    f.prototype = parent.prototype;
    c.prototype = new f();
}
我知道您不想直接复制原型,因此该函数充当代理-防止父原型的更改导致子原型出现问题。我不明白的是为什么要使用新函数?这不一样吗:

function inherit(child, parent) {
    var o = {}:
    o.prototype = parent.prototype;
    c.prototype = o;
}
有人能解释一下为什么他们是不同的,为什么他们选择了第一个版本而不是我的(看起来是做同样的事情?)-提前谢谢

编辑

下面是一些测试代码:

//inherit that uses a function as a proxy and creates a new instance as the child prototype
function inherit1(child, parent) {
    var f = function() {};
    f.prototype = parent.prototype;
    child.prototype = new f();
}

//inherit that stores prototype on an object and passes that to a prototype of the child
function inherit2(child, parent) {
    var o = {};
    o.prototype = parent.prototype;
    child.prototype = o;
}

//Begin test for inherit1
function parent1() {}
parent1.prototype.talk = function() {console.log("from parent1 prototype");};

function child1() {}

inherit1(child1, parent1);

var kid1 = new child1();

kid1.talk(); //"from parent1 prototype"

//Begin test from inherit2
function parent2() {}
parent2.prototype.talk = function() {console.log("from parent2 prototype");}

function child2() {}

inherit2(child2, parent2);

var kid2 = new child2();

kid2.talk(); //kid2.talk() is not a function 
kid2.prototype.talk() //"from parent2 prototype"

//这里发生了什么事?为了使原型继承工作,它必须从函数继承吗

那么它是
c
还是
child
?您想了解
[[Prototype]]
,以及它与函数的
原型的关系。您是否尝试在方法中更改child,并试着观察父对象是否更改?elclanrs:了解[[Prototype]]看起来它会解释你在我的编辑中看到的行为(包括测试和结果)?