gpt4 book ai didi

javascript - 对象继承

转载 作者:行者123 更新时间:2023-11-30 06:01:25 24 4
gpt4 key购买 nike

function Foo() {
this.SayFoo = function() {
console.log('Foo');
};
}

function Bar() {
this.SayBar = function() {
console.log('Bar');
};
}

Foo.prototype = new Bar();

var fooBar = new Foo();
fooBar.SayBar();

这显然有效,但这是正确的方法吗?

是否有任何方法可以利用 jQuery 的 $.extend 或类似的东西来实现相同的继承结果?

在这种情况下,包括除 jQuery 之外的其他框架不是一个选项。

最佳答案

在 JavaScript 中实际上有多种继承方式:新古典主义、原型(prototype)和函数式。 Douglas Crockford 对新古典继承——您在上面使用的方法,以及大多数 Java/C# 开发人员认为最自然的方法,只有坏话要说。原因围绕着你必须做的所有笨拙的事情来让它正确 - 设置原型(prototype),设置构造函数等。此外,将原型(prototype)设置为父类的 new 实例,就像你一样有上面的,通常是强烈反对的,我相信是因为它使使用基本 ctor 处理参数变得复杂。

如果您真的被新古典主义方法所吸引,这里有一个 great link这真的过去了。

我在这里为你重现的关键部分:

function Inherit(sub,super){
var thinF = function(){};
thinF.prototype = super.prototype;
sub.prototype = new thinF();
sub.prototype.constructor = sub;
sub.super = super.prototype;
if( super.prototype.constructor == Object.prototype.constructor ){
super.prototype.constructor = super;
}
}

FWIW 下面是一个函数继承的例子,它也强调了一些你不会通过新古典方法得到的东西:封装/信息隐藏。

function eventRaiser(protectedStuff) {
protectedStuff = protectedStuff || {};
var that = {};
var events = {}; //private

protectedStuff.raise = function(key) {
if (!events[key]) return;
for (var i = 0; i < events[key].funcs.length; i++)
events[key].funcs[i].apply(null, Array.prototype.slice.call(arguments, 1));
};

that.subscribe = function(key, func) {
if (!events[key])
events[key] = { name: key, funcs: [] };
events[key].funcs.push(func);
};

return that;
}

function widget() {
var protectedStuff = {};
var that = eventRaiser(protectedStuff);

that.doSomething = function() {
alert("doing something");
protectedStuff.raise("doStuffEvent");
};

return that;
}

$(function() {
var w = widget();
w.subscribe("doStuffEvent", function(){ alert("I've been raised"); });
w.doSomething();

w.protectedStuff.raise("doStuffEvent"); //error!!!!! raise is protected
w.raise("doStuffEvent"); //and this obviously won't work
});

关于javascript - 对象继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8250090/

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