简体   繁体   English

Javascript中的继承:为什么这段代码什么都不做?

[英]Inheritance in Javascript: Why does this code do nothing?

What is the problem with that code? 该代码有什么问题?

var t={a:1};
var g={b:2};
g.prototype=new t();
alert(g.a); //do nothing

The variable t contains an object, not a function, so you can't use it like an object constructor. 变量t包含一个对象,而不是一个函数,因此您不能像使用对象构造函数那样使用它。

You can use the object as prototype, but you need a constructor to make use of the prototype: 您可以将对象用作原型,但需要构造函数才能使用原型:

var t = { a: 1 };
function g() {
  this.b = 2;
}
g.prototype = t;
alert(new g().a);

Demo: http://jsfiddle.net/Guffa/WeuPG/ 演示: http//jsfiddle.net/Guffa/WeuPG/

You use new and constructors to create Objects, but what you have as t and g now are Objects already. 您使用new和构造函数创建对象,但是现在t和g已经是对象。

This should work; 这应该起作用;

function t(){
  this.a = 1;
}

function g(){
  this.b = 2;
}

g.prototype = new t();

alert(new g().a); // 1

Constructor must be a function. 构造函数必须是一个函数。

This is a very good article on inheritance 这是一篇很好的关于继承的文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM