JavaScript OOP:Uncaught TypeError:不是函数

时间:2016-05-30 16:19:40

标签: javascript oop javascript-objects

创建对象时遇到问题。控制台说最后一行有问题。请告诉它应该如何,我更熟悉Java,所以这对我来说有点混乱。

var dog = {
        name:"Dog",
        age:"11",
        getName : function() {
            alert(this.name);       
        }
    }   

    function Dog(name, age) {
        this.name = name;
        this.age = age; 
    }

    var d1 = new Dog("Rex", 8);
    d1.getName();

3 个答案:

答案 0 :(得分:3)

您的dog只是一个简单的对象字面值,
这意味着您的getName与其绑定,而不是Dog

您可以将该功能改为method Dog



/*var dog = {
  name:"Dog",
  age:"11",
  getName : function() {
    alert(this.name);       
  }
}*/ 

function Dog(name, age) {
  this.name = name;
  this.age = age; 
}

Dog.prototype.getName = function() {
  console.log( this.name );
}

var d1 = new Dog("Rex", 8);
d1.getName(); // "Rex"




这是一个使用settings"默认值"

的变体



function Dog() {
  this.name = "Dog"; // Default name
  this.age = 11;     // Default age
}

Dog.prototype.getName = function() {
  console.log( this.name );
}

var d1 = new Dog();
d1.name = "Rex";    // Override default name
d1.getName(); // "Rex"




答案 1 :(得分:2)

您可以使用带语法糖的在ES6中正确创建对象 在你的例子中,这样写:

'use strict';
class Dog{
  constructor(name, age){
    this.name = name;
    this.age = age;
  }
  getName(){
    console.log(this.name);
  }
}

let doggy = new Dog("krypto", 125);
doggy.getName();

答案 2 :(得分:1)

JavaScript中的传统OO

function Dog(name, age) {
    this.name = name || "Dog";// if the name is not given, it defaults to "Dog"
    this.age = age || "11"; 
}

Dog.prototype.getName =  function() {
    alert(this.name); 
}

var d1 = new Dog("Rex", 8);
d1.getName();

JavaScript中的更多显式OO

function createDog(name, age) {
    // create a new dog and return it
    var dog = {
        name: name || "Dog",// if the name is not given, it defaults to "Dog"
        age: age || "11"
    };
    return dog;
}

createDog.getName =  function(dog) {
    // explicit dog as 1st parameter
    alert(dog.name); 
}

//createDog is a normal function that returns something, no "new" needed
var d1 = createDog("Rex", 8);
createDog.getName(d1);