原型未按预期工作

时间:2014-11-27 15:00:17

标签: javascript jquery asp.net prototype

我使用以下代码来学习JS原型以及如何使用对象,(在我在网上阅读它之后我刚接触到JS ...)我想创建一个其他类可以使用的根对象并扩展 不确定我是否正确...目前我在声音上有错误(无法设置未定义的属性'声音',任何想法我做错了或者可能有更好的方法来写它,(对我而言,这是第三稿...... :))

var obj = function(name){

    this.name  = name;
};

obj.prototype.getName = function(){
    return this.name;
}

var person = new obj("Bill");

console.log(person.getName());


var animal = new obj();

animal.prototype.sound = function(sound){
    console.log(sound)
}


var dog = new animal();


dog.sound("wof");

3 个答案:

答案 0 :(得分:1)

这是因为声音未定义 - 该属性不存在。

创建具有声音属性的对象的简单方法就是这样(使用jquery):

var animal = { walk: function(){ return 'animal is walking'; }, legs: 4  }

var dog = $.extend({ sound: '' }, animal); 

dog.sound = 'woof';

你的例子无法工作的原因是你已经实例化了一个新的obj实例 - 它没有声音属性。所以你需要一种机制来扩展你实例化的对象。所以在我的例子中,我向你展示了一种快速简便的方法。

答案 1 :(得分:1)

您正在尝试进行继承

你必须做

var animal = function () {}
animal.prototype = new obj();
animal.prototype.constructor=animal;

src:http://phrogz.net/js/classes/OOPinJS2.html

另一方面,您可能想知道可以使用:

obj.prototype.__defineGetter__("name", function () { return this.n; /* where n is the name */ });

并像那样使用

var a = new obj("foo");
console.log(a.name);

答案 2 :(得分:0)

new obj();返回一个对象而不是函数,所以当你调用

var animal = new obj();

animal变量将填充一个非函数的对象。这句话

var dog = new animal();

返回undefined因为动物不是函数(构造函数)。请注意,运算符new仅用于不用于文字对象的函数

有关此主题的更多信息,请查看this question


一个简单的JavaScript继承模式

首先定义一个基类(JS中没有类概念,但我更方便地使用它)

function Obj(name){
    this.name = name;
}
Obj.prototype.setName = function(name){
    this.name = name;
}

接下来,您可以定义一个animal类,该类正在扩展obj类。

function Animal(name, legs){ 
    // This is its own property
    this.legs = legs;
    // This is accessible via prototype chain
    this.setName(name);
}

// link this class to the obj class
Animal.prototype = new Obj();

此模式的可视化架构将是:

    Animal
  +------------+  
  | legs       |           Obj
  | __proto__  | -----> +-----------+  
  +------------+        | name      |         prototype object for Obj
                        | __proto__ | -------> +--------------------+  
                        +-----------+          | setName function   |  
                                               +--------------------+

更新#1 要声明另一个类Person,例如,您可能希望这样做:

function Person(name, addr, phoneNo){
    this.name = name;  // This is inherited from the Obj class
    this.addr = addr;  // Its own property
    this.phoneNo = phoneNo; // Its own propert
    this.legs = 2; // This is from Animal 
}

Person.prototype = new Animal();