如何在JavaScript中继承父对象的属性 [英] How to inherit properties from parent object in JavaScript

查看:91
本文介绍了如何在JavaScript中继承父对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一些对象和包装类来简化一些表单检查方法。我已经研究了JavaScript继承的标准例程,但是在运行代码时我遇到了一个相当奇怪的错误。以下是要点:

 功能 FooParent(a){
this .prop = a;
.val = a.value; // *
}
var elem = new FooParent( document .getElementById( someDomElement) ;
alert(elem.val);
// 警告表单元素的值no概率!



如果我然后将此块添加到相同的代码:

  function  FooKid(a,b){
FooParent.call( this ,b);
this .kidProp = b;
}
FooKid.prototype = new FooParent ();
FooKid.prototype。构造函数 = FooKid;
var elem2 = new FooKid( document .getElementById( someDomElement);
alert(elem2.val);
// 最后两行中的变量声明是无关紧要的,当我运行时代码在第3行中断在添加最后一个块之后。



firebug给我的错误是在父对象中 this.val = a.value; 现在在尝试从它继承之前工作时是未定义的。我也试过...... this.val = this.prop.value ,和 this.val = prop.value (所有都应该指向相同的事情所以最后,我的问题是:为什么这个代码会破坏?bug在哪里?

解决方案

javascript继承:

  if  typeof  Object.create!= = '  function'){
Object.create = function (o){
function F(){}
F.prototype = o;
< span class =code-keyword> return new F();
};
}

var newObject1 = Object.create({key1:' valuekke'});
var newObject2 = Object.create(newObje ct1);


在你的代码中,FooParent期待一个参数''a''

在你的行中...

  new  FooParent(); 



...你还没有提供这个参数


I am trying to create some objects and wrapper classes to simplify some form checking methods. I have researched the standard routine for JavaScript inheritance but I am getting a rather odd error when running my code. Here is the gist:

function FooParent (a){
    this.prop = a;
    this.val = a.value;//*
}
var elem = new FooParent(document.getElementById("someDomElement");
alert(elem.val);
//alerts the value of the form element no prob!


If I then add this block to the same code:

function FooKid (a, b) {
    FooParent.call(this, b);
    this.kidProp = b;
}
FooKid.prototype = new FooParent();
FooKid.prototype.constructor = FooKid;
var elem2 = new FooKid(document.getElementById("someDomElement");
alert(elem2.val);
//the variable declaration in the last two lines is inconsequential, the code breaks on line 3 when I run it after adding the last block. 


The error that firebug gives me is that in the parent object this.val = a.value; is now undefined when it worked prior to trying to inherit from it. I also tried... this.val = this.prop.value, and this.val = prop.value (all should point to the same thing So in conclusion, my question is: why is this code breaking? Where is the bug?

解决方案

inheritance in javascript:

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

var newObject1 = Object.create({key1:'valuekke'});
var newObject2 = Object.create(newObject1);


In you code FooParent expects a param ''a''
In your line...

new FooParent();


...you haven''t provided this param.


这篇关于如何在JavaScript中继承父对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆