gpt4 book ai didi

JavaScript 继承

转载 作者:可可西里 更新时间:2023-11-01 01:52:06 26 4
gpt4 key购买 nike

Douglas Crockford似乎喜欢下面的继承方式:

if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
newObject = Object.create(oldObject);

我觉得还不错,但它与 John Resig 的 simple inheritance 有何不同?方法?

基本上它归结为

newObject = Object.create(oldObject);

对比

newObject = Object.extend();

我对理论很感兴趣。在实现方面似乎没有太大区别。

最佳答案

方法完全不同,Resig 技术创建构造函数,这种方法也称为经典继承 即:

var Person = Class.extend({
init: function(isDancing){
this.dancing = isDancing;
}
});

var p = new Person(true);

如您所见,Person 对象实际上是一个 constructor function ,与 new 运算符一起使用。

使用 Object.create 技术,继承是基于实例的,其中对象直接从其他对象继承,也称为原型(prototype)继承差异继承

关于JavaScript 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2939138/

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