我是 JavaScript 新手。我已经使用对象初始值设定项方法定义了一个对象。
var obj = { a : "A";
b : "B";
myFunc = function() {
alert("Hello"):
}
现在我想创建另一个对象,该对象将成为 Obj
的子对象。我怎样才能做到这一点。
var obj1 = new obj();
不工作。
最佳答案
首先,您有一个语法错误
myFunc = function() { ...
无论如何,这就是您想要的设置方式
function Foo() {
this.a = "A";
this.b = "B";
}
Foo.prototype.myFunc = function() {
alert("hello");
};
现在创建您的子对象
function Bar() {
Foo.call(this); // call parent constructor; optional
}
// setup child prototype
Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.constructor = Bar;
检查一下
var b = new Bar();
b instanceof Bar; // true
b instanceof Foo; // true
b.constructor.name; // Bar
b.myFunc; // "hello"
关于javascript - 从 javascript 中的对象初始值设定项继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20344341/