gpt4 book ai didi

javascript - JavaScript 中的继承

转载 作者:行者123 更新时间:2023-11-30 18:42:54 24 4
gpt4 key购买 nike

我正在读一本关于继承的 JS 书,我真的很困惑每一行在做什么。谁能告诉我我的理解是否正确。

function classA(sColor){
this.color = sColor;
this.sayColor = function (){
alert(this.color);
};
}

function ClassB(sColor, sName){
this.newMethod = classA; //assigning a reference to a parent class
this.newMethod(sColor); //calling the constructor of the parent class

//question: so what is 'this' then? from my understanding when we call 'new ClassB('a','b')'
//we instantiate a new object and that new object becomes the 'this' in this case. Does this
//line mean we are converting the this to classA?

delete this.newMethod; //deleting reference to the CONSTRUCTOR of the parent class

this.name = sName;
this.sayName = function(){
alert(this.name);
}

}

最佳答案

How this works

function ClassB(sColor, sName){
this.newMethod = classA;
this.newMethod(sColor);

delete this.newMethod;

this.name = sName;
this.sayName = function(){
alert(this.name);
}
}

这是一种平庸的方法

function ClassB(sColor, sName){
classA.call(this, sColor);

this.name = sName;
this.sayName = function(){
alert(this.name);
}
}

var f = new ClassB("green", "boy");
f.sayName(); // boy
f.sayColor(); // green

您基本上是使用this 对象调用classA 构造函数。

JavaScript 没有类,它只有对象和操作对象的函数。您的 ClassA 函数操作 thisClassB 也是如此。

ClassA 只是一个操作对象的函数。在这种情况下,它操作 context 对象,即 this。所有 ClassB 所做的就是说

  • 让 ClassA 操作this
  • 将名为 name 的属性添加到 this
  • 将名为sayName 的方法添加到this

奖励:

在 JavaScript 中有更好的 OO 方法

// A is a blueprint for an object with a method sayColor
var A = (function() {
var self = Object.create({});
self.sayColor = function() {
alert(this.color);
};
return self;
}());

// B is a blueprint for an object with methods sayColor and sayName
var B = (function() {
// clone the methods from A
var self = Object.create(A);
self.sayName = function() {
alert(this.name);
};
return self;
}());

// clone B and set the properties for name and color
var b = Object.create(B, {
name: { value: "boy" },
color: { value: "green" }
});

/* or use a factory

var bFactory = function(name, color) {
return Object.create(B, {
name: { value: name },
color: { value: boy }
});
}

b = bFactory("boy", "green");

*/

b.sayName();
b.sayColor();

使用Object.create这是 ES5 所以使用 ES5-shim以支持旧版浏览器。

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

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