本文介绍了将方法添加到js中的函数内部的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是来自我正在努力的挑战。有没有什么办法可以将引入方法添加到 personStore 对象中,而不使用关键字this。任何洞察力都将不胜感激。

我的解决方案:

  var personStore = {
//在这里添加代码
greet:function(){
console.log('Hello');
}
};

function personFromPersonStore(name,age){
var person = Object.create(personStore);
person.name = name;
person.age = age;
person.greet = personStore.greet;
return person;
};

personStore.introduce = function(){
console.log('我的名字是'+ this.name)
}

/ /挑战3测试者
sandra.introduce(); // - > Logs'我的名字是Sandra


解决方案

但是使用这个要简单得多。



这段代码传递名字属性作为参数,但由于该属性已经可以通过引入函数作为通过这个,这有点浪费。



var personStore = {//在这里添加代码greet:function(){console.log('Hello'); }}; function personFromPersonStore(name,age){var person = Object.create(personStore); person.name = name; person.age =年龄; person.greet = personStore.greet;返回者; }; personStore.introduce = function(nm){console.log('Hi,my name is'+ nm)} person1 = personFromPersonStore('Fred',21); person1.introduce(person1.name);


Hi this is from a challenge I was working on. Is there any way i can add the introduce method to the personStore object without using the keyword this. Any insight is greatly appreciated.

my solution:

var personStore = {
    // add code here
  greet: function (){
    console.log('Hello');
  }
};

function personFromPersonStore(name, age) {
  var person = Object.create(personStore);
  person.name = name;
  person.age = age;
  person.greet = personStore.greet;
  return person;    
};

personStore.introduce = function () {
  console.log('Hi, my name is ' + this.name)
}

//Challenge 3 Tester
sandra.introduce(); // -> Logs 'Hi, my name is Sandra
解决方案

You can, but using this is a lot simpler.

This code passes the name property as an argument, but as the property is already accessible to the introduce function as an internal property via this, it is a bit wasteful.

var personStore = {
    // add code here
  greet: function (){
    console.log('Hello');
  }
};

function personFromPersonStore(name, age) {
  var person = Object.create(personStore);
  person.name = name;
  person.age = age;
  person.greet = personStore.greet;
  return person;    
};

personStore.introduce = function (nm) {
  console.log('Hi, my name is ' + nm)
}

person1=personFromPersonStore('Fred',21);
person1.introduce(person1.name);

这篇关于将方法添加到js中的函数内部的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 17:38